Search code examples
c#ms-wordnetoffice

How add header with .NetOffice library


I'm using NetOffice to create Word documents.

There is little documentation and I'm struggling to add a header. Can anybody help?


Solution

  • You have to use the Word.Section.Headers property, in the example below I've put an image right-aligned on the page header

        foreach (Word.Section section in newDocument.Sections)
            {
                string picturePath = @"D:\Desktop\test.png";
                section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.InlineShapes.AddPicture(picturePath);
                section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
            }
    

    To add some text use:

        foreach (Word.Section section in newDocument.Sections)
           section.Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Text = "TEST";
    

    Hope this helps to investigate further.