Add a header only into the first page of a document

A document can have one or more pages. It is probably easy to add a header for all pages of the document. If you want to add the header only for the first page of the document, Spire.Doc for .NET component can provide you an easy and flexible solution to handle it. The following steps will guide how to add a header into the first page of a document using Spire.Doc for .NET component in C#. In the example, the header is got from an existing document.

Step 1: Load a word document, documen1.docx.

Document document1 = new Document();
document1.LoadFromFile("D:\\document1.docx");

Step 2: Get the header of document1.docx.

HeaderFooter header = document1.Sections[0].HeadersFooters.Header;

Step 3: Load another word document which will be added the header, document2.docx.

Document document2 = new Document();
document2.LoadFromFile("D:\\document2.docx");

Step 4: Get the first page header of document2.docx.

HeaderFooter firstPageHeader = document2.Sections[0].HeadersFooters.FirstPageHeader;

Step 5: Specify that the current section has a different header/footer for the first page.

foreach (Section section in document2.Sections)
{
section.PageSetup.DifferentFirstPageHeaderFooter = true;
}

Step 6: Removes all child objects in firstPageHeader.

firstPageHeader.Paragraphs.Clear();

Step 7: Add all child objects of the header to firstPageHeader.

foreach (DocumentObject obj in header.ChildObjects)
{
firstPageHeader.ChildObjects.Add(obj.Clone());
}

Step 8: Save document2.docx to a new document, header.docx.

document2.SaveToFile("D:\\Header.docx"", FileFormat.Docx);

Full code:

Document document1 = new Document();
document1.LoadFromFile(@"..\..\document1.docx");
Document document2 = new Document();
document2.LoadFromFile(@"..\..\document2.docx");
HeaderFooter header = document1.Sections[0].HeadersFooters.Header;
HeaderFooter firstPageHeader = document2.Sections[0].HeadersFooters.FirstPageHeader;

foreach (Section section in document2.Sections)
{
section.PageSetup.DifferentFirstPageHeaderFooter = true;
}

firstPageHeader.Paragraphs.Clear();
foreach (DocumentObject obj in header.ChildObjects)
{
firstPageHeader.ChildObjects.Add(obj.Clone());
}

document2.SaveToFile("Header.docx", FileFormat.Docx);

Screenshots:

document1.docx:

Add a header only into the first page

document2.docx:

Add a header only into the first page

Header.docx:

Add a header only into the first page

Additional Info

  • tutorial_title:
Last modified on Friday, 03 September 2021 03:56