Corrupt document after calling AddAlternativeFormatImportPart using OpenXml
c#, docx, ms-word, openxml, openxml-sdk
Solution
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();
}
Problem
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(); ```