0

I am adding html string to the header of a word document dynamically generated using OpenXml

public static void ApplyHeader(WordprocessingDocument doc)
{
    // Get the main document part.
    MainDocumentPart mainDocPart = doc.MainDocumentPart;

    HeaderPart headerPart1 = mainDocPart.AddNewPart<HeaderPart>("r97");

    Header header1 = new Header();

    string html =
    @"<div style =\"display:block;max-width:750px; margin:0 auto; \"> <img src = \"/images/header.jpg\" style= \"max-width:100%;\" /></div><p>Continuation Sheet</p>";

    string altChunkId = "AltChunkId2";

    AlternativeFormatImportPart chunk = mainDocPart.AddAlternativeFormatImportPart("application/xhtml+xml", altChunkId);
    using (Stream chunkStream = chunk.GetStream())
    {
        using (StreamWriter stringWriter = new StreamWriter(chunkStream, Encoding.UTF8)) //Encoding.UTF8 is important to remove special characters
        {
            stringWriter.Write(html);
        }
    }
    AltChunk altChunk = new AltChunk();
    altChunk.Id = altChunkId;

    // first header
    Paragraph paragraph1 = new Paragraph() { };

    paragraph1.InsertAt(altChunk,0);
    header1.Append(paragraph1);
    headerPart1.Header = header1;


    SectionProperties sectionProperties1 = mainDocPart.Document.Body.Descendants<SectionProperties>().FirstOrDefault();
    if (sectionProperties1 == null)
    {
        sectionProperties1 = new SectionProperties() { };
        mainDocPart.Document.Body.Append(sectionProperties1);
    }
    HeaderReference headerReference1 = new HeaderReference() { Type = HeaderFooterValues.Default, Id = "r97" };

    sectionProperties1.InsertAt(headerReference1, 0);
}

Now after I open the word document, it gives the following error 'Microsoft cannot open this file because some parts are missing or invalid.' How can I solve this error?

Ashita Shah
  • 139
  • 1
  • 11
  • The error message indicates the content you've added results in invalid Word Open XML. If you want to add it to the Header, why are you adding it to the document body in the code you show us. See https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.packaging.headerpart.addalternativeformatimportpart?view=openxml-2.8.1#DocumentFormat_OpenXml_Packaging_HeaderPart_AddAlternativeFormatImportPart_System_String_System_String_. – Cindy Meister May 25 '18 at 12:24
  • Also, it's not clear why you feel you need to hard-code a RelationshipId. You might find this useful, as far as adding and managing a new HeaderPart goes https://stackoverflow.com/questions/46560269/copy-header-and-footer-to-all-other-documents-openxml. – Cindy Meister May 25 '18 at 12:25
  • the html string is just sample. I want to add this string as the header "

    Continuattionb

    "
    – Ashita Shah May 25 '18 at 12:34

0 Answers0