将HTML转换为Word Docx并保留样式

4

我知道已经有类似的问题了,而且建议使用Open XML等。

我正在使用Open XMl,但它只能处理内联样式。

是否有解决方案,或者除了Open XML之外,还有更好的方式将html转换为docx?

谢谢!

1个回答

7
您可以使用像这里描述的工具来内联CSS文件。
然后,执行转换(改编自Eric White的博客):
using (WordprocessingDocument myDoc =
    WordprocessingDocument.Open("ConvertedDocument.docx", true))
{
    string altChunkId = "AltChunkId1";
    MainDocumentPart mainPart = myDoc.MainDocumentPart;
    var chunk = mainPart.AddAlternativeFormatImportPart(
        AlternativeFormatImportPartType.Html, altChunkId);

    using (FileStream fileStream = File.Open("YourHtmlDocument.html", FileMode.Open))
    {
        chunk.FeedData(fileStream);
    }
    AltChunk altChunk = new AltChunk() {Id = altChunkId};

    mainPart.Document.Body.InsertAfter(
               altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
    mainPart.Document.Save();
}

这并不完全是将HTML转换为DOCX,而是将 YourHtmlDocument.html 追加到 ConvertedDocument.docx。如果 ConvertedDocument.docx 最初是空的,则此方法有效地进行了转换。
每当您使用 AltChunk 构建文档时,您的HTML将嵌入文档,直到下一次在Word中打开文档。此时,HTML将转换为 WordProcessingML 标记。这只有在文档不会在MS Word中打开时才会成为问题。如果您要上传到Google文档、在OpenOffice中打开或使用COM转换为PDF,则OpenXML将不足够。在这种情况下,您可能需要使用付费工具,如Aspose.Words

如果之前没有插入段落,则 Elements<Paragraph>().Last() 会导致崩溃,因为找不到 Last()。请改用 mainPart.Document.Body.InsertAfterSelf(altChunk); - Rogier van het Schip
如何在Word文档的页眉和页脚中插入altchunk? - Ashita Shah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接