首页 文章

使用OpenXML SDK创建文档时,OpenXML Powertools HtmlConverter失败

提问于
浏览
1

我使用OpenXML SDK 2.5编写了一个Word文档,当我在MS Office中预览时,这些文档会给出预期的外观和格式 .

现在我需要将此文档转换为HTML文档,我在OpenXML Powertools中了解了 HtmlConverter ,并尝试使用它,使用OpenXML电源工具将Docx转换为Html失败,并将 NullReferenceException 表示为 Part 作为空值参数 .

为了调查我将两个文件重命名为ZIP以便检查其内容,使用MS Office创建的文档下方捕获的 document.xml 标记位于顶部,使用OpenXML SDK创建的文档标记位于底部,

enter image description here

我怀疑 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());
}

1 回答

  • 1

    要查看文件差异,我建议您将使用SDK创建的文件与使用Word创建的文件进行比较 . 您可以使用Open XML Productivity Tool执行此操作 . 要安装该工具,请按照下列步骤操作:

    • 转到download link

    • 单击“红色下载”按钮 .

    • 在下一个屏幕上,只需单击OpenXMLSDKToolV25.msi旁边的框

    • 然后单击“下一步”,将自动在浏览器中开始下载 .

    安装后,启动该工具 .

    要比较2个OpenXml文件,请单击中间的“比较文件”按钮,将显示差异 .

    enter image description here

    在比较模式下打开文件后,选择右侧部件选择器区域中的主文档部件,然后单击“查看部件差异”按钮 .

    enter image description here

    这将向您展示不同的XML . 如果单击“查看包代码”,则会生成C#代码,如果需要,可以在这两个文件之间产生差异 .

    Pro tip - 仅生成构建由Word创建的文件所需的代码,使用“打开文件”按钮在非比较模式下在 生产环境 力工具中打开它 . 然后单击“反映代码”以生成重新生成Word生成文件的精确克隆所需的C#代码 .

相关问题