Skip to main content
A newer version of this page is available. .

How to: Create and Modify Header

  • 3 minutes to read

The following article explains how to create and modify a document header.

Create a Header

To create a document header, select the section where it is going to be located. To check whether this section already has a header, use the Section.HasHeader property.

The Section.BeginUpdateHeader method is used to start the process. It also creates a new header of the specified HeaderFooterType type. If the type is not specified, the HeaderFooterType.Primary header will be created.

To work with the document header, use the Document.ChangeActiveDocument method. Note that if this method is not used, the wrong header can be selected and the follow-up actions may fail.

Use the Section.EndUpdateHeader to finish working with the header.

Section firstSection = document.Sections[0];
// Create an empty header.
SubDocument newHeader = firstSection.BeginUpdateHeader();
firstSection.EndUpdateHeader(newHeader);
// Check whether the document already has a header (the same header for all pages).
if (firstSection.HasHeader(HeaderFooterType.Primary))
{
    SubDocument headerDocument = firstSection.BeginUpdateHeader();
    document.ChangeActiveDocument(headerDocument);
    document.CaretPosition = headerDocument.CreatePosition(0);
    firstSection.EndUpdateHeader(headerDocument);
}

Modify Header

To modify the header, specify the section to which the header belongs and use the Section.BeginUpdateHeader method to open it for modifying. To insert additional content to the header, use the SubDocument.InsertText or ShapeCollection.InsertPicture method. Use the Section.EndUpdateHeader to complete the modification.

The following code snippet opens the first section’s header for editing. The header type is HeaderFooterType.First, so it is displayed for the first page only if the corresponding mode is enabled (use the Section.DifferentFirstPage property). Then, the text string and a PAGE field are inserted and the Section.EndUpdateHeader method is called to finalize the modification.

document.AppendSection();
Section firstSection = document.Sections[0];
// Modify the header of the HeaderFooterType.First type.
SubDocument myHeader = firstSection.BeginUpdateHeader(HeaderFooterType.First);
DocumentRange range = myHeader.InsertText(myHeader.CreatePosition(0), " PAGE NUMBER ");
Field fld = myHeader.Fields.Create(range.End, "PAGE \\* ARABICDASH");
myHeader.Fields.Update();
firstSection.EndUpdateHeader(myHeader);
// Display the header of the HeaderFooterType.First type on the first page.
firstSection.DifferentFirstPage = true;