使用OpenXml调用AddAlternativeFormatImportPart后损坏的文档 [英] Corrupt document after calling AddAlternativeFormatImportPart using OpenXml

查看:257
本文介绍了使用OpenXml调用AddAlternativeFormatImportPart后损坏的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在.docx文件中创建AddAlternativeFormatImportPart,以便通过AltChunk在文档中引用它.问题是下面的代码导致docx文件被Word损坏读取,无法打开.

I am trying to create an AddAlternativeFormatImportPart in a .docx file in order to reference it in the document via an AltChunk. the problem is that the code below causes the docx file to read as corrupted by Word and cannot be opened.

        string html = "some html code."

        string altChunkId = "html234";
        var document = WordprocessingDocument.Open(inMemoryPackage, true);
        var mainPart = document.MainDocumentPart.Document;
        var mainDocumentPart = document.MainDocumentPart;

        AlternativeFormatImportPart chunk = mainDocumentPart.AddAlternativeFormatImportPart
            (AlternativeFormatImportPartType.Xhtml, altChunkId);

        Stream contentStream = chunk.GetStream(FileMode.Open,FileAccess.ReadWrite);
        StreamWriter contentWriter = new StreamWriter(contentStream);
        contentWriter.Write(html);
        contentWriter.Flush();

        {
          ...
        }

        mainPart.Save();

推荐答案

我认为这可能是您从AlternativeFormatImportPart处理流的方式.像下面的示例一样,尝试使用FeedData.

I think it might be how you are handeling the stream from the AlternativeFormatImportPart. Try using FeedData instead, like in my example below.

        StringBuilder xhtmlBuilder = new StringBuilder();
        xhtmlBuilder.Append("<html>");
        xhtmlBuilder.Append("<body>");
        xhtmlBuilder.Append("<b>Hello world!</b>");
        xhtmlBuilder.Append("</body>");
        xhtmlBuilder.Append("</html>");

        using (WordprocessingDocument doc = WordprocessingDocument.Open(inputFilePath, true))
        {
            string altChunkId = "chunk1";
            AlternativeFormatImportPart chunk = doc.MainDocumentPart.AddAlternativeFormatImportPart
                (AlternativeFormatImportPartType.Xhtml, altChunkId);

            using (MemoryStream xhtmlStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(xhtmlBuilder.ToString())))
            {
                chunk.FeedData(xhtmlStream);

                AltChunk altChunk = new AltChunk();
                altChunk.Id = altChunkId;
                doc.MainDocumentPart.Document.Body.Append(altChunk);
            }

            doc.MainDocumentPart.Document.Save();

        }

这篇关于使用OpenXml调用AddAlternativeFormatImportPart后损坏的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆