Я занят, пытаясь преобразовать html в текстовый документ, но получаю странную ошибку:
Исключение: «System.NullReferenceException» в Service.dll
Object ссылка не установлена на экземпляр объекта.
, и он указывает мне на эту строку кода:
var paragraphs = converter.Parse(html);
Но когда я проверяю в отладчике, он возвращает данные , поэтому я понятия не имею, почему эта ошибка выбрасывается. Мои html и изображения сохраняются во временной папке, и это выглядит так:
![enter image description here](https://i.stack.imgur.com/ls9IQ.png)
Вот мой WordReport.cs
protected override MemoryStream GenerateScorecardReport()
{
HtmlReportService.GenerateReportHtmlFile(ReportParameters, HtmlFilePath, IsVA);
string directoryName = Path.GetDirectoryName(HtmlFilePath) + "\\";
var docxFilename = directoryName + Guid.NewGuid() + ".docx";
return SaveHtmlAsDocX(docxFilename, HtmlFilePath);
}
public override MemoryStream GenerateScorecardSummaryReport(Guid scorecardId, bool hideScenario)
{
throw new NotImplementedException();
}
public override MemoryStream GenerateStatutoryReport(string reportHtml, string fileName)
{
string localRoot = Config.ReportTempDir + "\\";
DirectoryInfo di = Directory.CreateDirectory(localRoot); // Method does nothing if path exists.
var tempFileName = localRoot + Guid.NewGuid() + "\\" + Guid.NewGuid() + ".html";
CreateReportDirectory(tempFileName);
try
{
return ReturnDocxFromHtml(reportHtml, tempFileName);
}
finally
{
CleanupTempDirectory(Path.GetDirectoryName(tempFileName));
}
}
и это мой Html2WordOpenXMLXconverter.cs
public static string Convert(string htmlSrcFilePath, bool addTableOfContents = true)
{
string wordDestFilePath = Path.GetDirectoryName(htmlSrcFilePath) + "\\" + Path.GetFileNameWithoutExtension(htmlSrcFilePath) + ".docx";
FileInfo SrcFile = new FileInfo(htmlSrcFilePath);
if (SrcFile.Exists == false)
{
throw new Exception(htmlSrcFilePath + " doesn't exist.");
}
string html = File.ReadAllText(htmlSrcFilePath);
try
{
using (WordprocessingDocument package = WordprocessingDocument.Create(wordDestFilePath, WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = package.MainDocumentPart;
if (mainPart == null)
{
mainPart = package.AddMainDocumentPart();
new Document(new Body()).Save(mainPart);
}
if (addTableOfContents)
{
var sdtBlock = new SdtBlock();
//TODO Covert this to code base TOC generation
sdtBlock.InnerXml = GetTOC("Table Of Contents", 16);
package.MainDocumentPart.Document.Body.AppendChild(sdtBlock);
var settingsPart = package.MainDocumentPart.AddNewPart<DocumentSettingsPart>();
settingsPart.Settings = new Settings { BordersDoNotSurroundFooter = new BordersDoNotSurroundFooter() { Val = true } };
settingsPart.Settings.Append(new UpdateFieldsOnOpen() { Val = true });
}
int pFrom = html.IndexOf("<style>") + "<style>".Length;
int pTo = html.LastIndexOf("</style>");
string result = html.Substring(pFrom, pTo - pFrom);
HtmlConverter converter = new HtmlConverter(mainPart);
//{
//};
converter.ExcludeLinkAnchor = true;
converter.RefreshStyles();
converter.ImageProcessing = ImageProcessing.AutomaticDownload;
Body body = mainPart.Document.Body;
converter.ConsiderDivAsParagraph = false;
var paragraphs = converter.Parse(html);
for (int i = 0; i < paragraphs.Count; i++)
{
body.Append(paragraphs[i]);
}
mainPart.Document.Save();
}
}
catch (Exception ex)
{
logger.LogError("Failed to create COM objects.", ex);
throw;
}
return wordDestFilePath;
}
, и это моя строка c строковая функция для добавления оглавления:
private static Paragraph SetHeading1(this Paragraph p)
{
var pPr = p.Descendants<ParagraphProperties>().GetEnumerator().Current;
pPr.ParagraphStyleId = new ParagraphStyleId() { Val = "Heading1" };
return p;
}
private static string GetTOC(string title, int titleFontSize)
{
return $@"<w:sdt>
<w:sdtPr>
<w:id w:val=""-493258456"" />
<w:docPartObj>
<w:docPartGallery w:val=""Table of Contents"" />
<w:docPartUnique />
</w:docPartObj>
</w:sdtPr>
<w:sdtEndPr>
<w:rPr>
<w:rFonts w:asciiTheme=""minorHAnsi"" w:eastAsiaTheme=""minorHAnsi"" w:hAnsiTheme=""minorHAnsi"" w:cstheme=""minorBidi"" />
<w:b />
<w:bCs />
<w:noProof />
<w:color w:val=""auto"" />
<w:sz w:val=""22"" />
<w:szCs w:val=""22"" />
</w:rPr>
</w:sdtEndPr>
<w:sdtContent>
<w:p w:rsidR=""00095C65"" w:rsidRDefault=""00095C65"">
<w:pPr>
<w:pStyle w:val=""TOCHeading"" />
<w:jc w:val=""center"" />
</w:pPr>
<w:r>
<w:rPr>
<w:b />
<w:color w:val=""2E74B5"" w:themeColor=""accent1"" w:themeShade=""BF"" />
<w:sz w:val=""{titleFontSize * 2}"" />
<w:szCs w:val=""{titleFontSize * 2}"" />
</w:rPr>
<w:t>{title}</w:t>
</w:r>
</w:p>
<w:p w:rsidR=""00095C65"" w:rsidRDefault=""00095C65"">
<w:r>
<w:rPr>
<w:b />
<w:bCs />
<w:noProof />
</w:rPr>
<w:fldChar w:fldCharType=""begin"" />
</w:r>
<w:r>
<w:rPr>
<w:b />
<w:bCs />
<w:noProof />
</w:rPr>
<w:instrText xml:space=""preserve""> TOC \o ""1-3"" \h \z \u </w:instrText>
</w:r>
<w:r>
<w:rPr>
<w:b />
<w:bCs />
<w:noProof />
</w:rPr>
<w:fldChar w:fldCharType=""separate"" />
</w:r>
<w:r>
<w:rPr>
<w:noProof />
</w:rPr>
<w:t>No table of contents entries found.</w:t>
</w:r>
<w:r>
<w:rPr>
<w:b />
<w:bCs />
<w:noProof />
</w:rPr>
<w:fldChar w:fldCharType=""end"" />
</w:r>
</w:p>
</w:sdtContent>
</w:sdt>
<w:p>
<w:r>
<w:br w:type=""page"" />
</w:r>
</w:p>";
}
}
}