我使用 OpenXML SDK 2.5 编写了一个 Word 文档,当我在 MS Office 中预览它时,该文档给出了预期的外观和格式。
现在我需要将此文档转换为 HTML 文档,我在 OpenXML Powertools 中了解到HtmlConverter
,并尝试使用它,使用 OpenXML 电动工具的 Docx 到 Html 转换失败,NullReferenceException
并声明Part
为空值参数。
为了调查,我创建了新的 Word 文档(在 MS Word 中),其中包含我文档的确切内容;此文件已成功转换为 Html,所以问题出在我用 C# 创建的文档上。我发现两者的文件大小各不相同(从 MS Word 创建的文档更重,使用 OpenXML SDK 创建的文档似乎更轻);我已将这两个文件重命名为 ZIP 以检查其内容,document.xml
使用 MS Office 创建的以下文档的标记位于顶部,使用 OpenXML SDK 创建的文档标记位于底部,
我怀疑失败HtmlConverter
是由于这些标记更改。我的假设正确吗?如果是这样如何在文档中添加这些额外的标记。这是我用来创建 Word 文件的代码。
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(@"D:\15052018.docx", WordprocessingDocumentType.Document))
{
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
Body body = mainPart.Document.AppendChild(new Body());
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
RunProperties rpr = new RunProperties(new RunFonts() { Ascii = "Times New Roman" });
run.PrependChild<RunProperties>(rpr);
run.AppendChild(new Text("Welcome"));
wordDocument.Save();
wordDocument.Close();
}
对于 HTML 转换,
using (WordprocessingDocument doc = WordprocessingDocument.Open(@"D:\15052018.docx", true))
{
HtmlConverterSettings settings = new HtmlConverterSettings() { PageTitle = "My Page Title" };
var html = HtmlConverter.ConvertToHtml(wDoc: doc, htmlConverterSettings: settings);
File.WriteAllText(@"D:\Test1.html", html.ToStringNewLineOnAttributes());
}