I am merging two Word documents with OpenXML SDK but get a corrupt document when copying an image into a header

好久不见. 提交于 2019-12-06 15:56:28

As I said in the comment on the question, the code to include the images into the header and footer was fine - it did the trick.

How I solved the problem of the corrupt file that my code (elsewhere) was creating was by a bit of trial and error. As other contributors have said, the documentation around OpenXML is, to put it mildly, not very good. So there might be another resolution to this problem, and maybe my "solution" just works because of some other side effects.

Anyway, I have some code which looks like this:

    private MemoryStream _memoryStream;
    private WordprocessingDocument _wordDocument;
      ...
    _wordDocument = WordprocessingDocument.Open(_memoryStream, true);
      ... 

    private void ReopenDocument() {
      _wordDocument.Package.Flush();
      _wordDocument.Close();
      MemoryStream newStream = new MemoryStream();
      _memoryStream.WriteTo(newStream);
      _memoryStream.Close();
      _memoryStream = newStream;
      _memoryStream.Position = 0L;
      _wordDocument = WordprocessingDocument.Open(_memoryStream, true);
    }

If I call the ReopenDocument method immediately prior to writing the _memoryStream to a FileStream, then the corruption is avoided.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!