Header and Footer

Header and Footer (12)

The height of headers and footers can be adjusted by using the HeaderDistance and the FooterDistance properties. The detail steps of how to adjust the height of headers and footers in a word document using Spire.Doc are shown below.

Detail steps:

Step 1: Instantiate a Document object and load the word document.

Document doc = new Document();
doc.LoadFromFile("Headers and Footers.docx");

Step 2: Get the first section.

Section section = doc.Sections[0];

Step 3: Adjust the height of headers and footers in the section.

section.PageSetup.HeaderDistance = 100;
section.PageSetup.FooterDistance = 100;

Step 4: Save the file.

doc.SaveToFile("Output.docx", FileFormat.Docx2013);

Screenshot:

Header:

Adjust the Height of Headers and Footers in a Word document in C#

Footer:

Adjust the Height of Headers and Footers in a Word document in C#

Full code:

//Instantiate a Document object
Document doc = new Document();
//Load the word document
doc.LoadFromFile("Headers and Footers.docx");

//Get the first section
Section section = doc.Sections[0];

//Adjust the height of headers in the section
section.PageSetup.HeaderDistance = 100;

//Adjust the height of footers in the section
section.PageSetup.FooterDistance = 100;

//Save the document
doc.SaveToFile("Output.docx", FileFormat.Docx2013);

There are up to three kinds of headers and footers on a word document (for first, even and odd pages) and Spire.Doc supports to insert footer and header to the word document in C#. In the following example, we will load a document with headers and footers, and we will remove all footers from all sections, but leaves headers.

Step 1: Create a new instance of word document and load the sample document from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Get the first section from file.

Section section = doc.Sections[0];

Step 3: Traverse the word document and clear all footers in different type.

foreach (Paragraph para in section.Paragraphs)
{
    foreach (DocumentObject obj in para.ChildObjects)
    {
        HeaderFooter footer;
        footer = section.HeadersFooters[HeaderFooterType.FooterFirstPage];
        if (footer != null)
            footer.ChildObjects.Clear();

        footer = section.HeadersFooters[HeaderFooterType.FooterOdd];
        if (footer != null)
            footer.ChildObjects.Clear();

        footer = section.HeadersFooters[HeaderFooterType.FooterEven];
        if (footer != null)
            footer.ChildObjects.Clear();
                          
    }

Step 4: Save the document to file.

doc.SaveToFile("Result.docx", FileFormat.Docx2013);

Full codes of removing footers but keeping the header on word document:

static void Main(string[] args)
{

    Document doc = new Document();
    doc.LoadFromFile("Sample.docx");

    Section section = doc.Sections[0];

    foreach (Paragraph para in section.Paragraphs)
    {
        foreach (DocumentObject obj in para.ChildObjects)
        {
            HeaderFooter footer;
            footer = section.HeadersFooters[HeaderFooterType.FooterFirstPage];
            if (footer != null)
                footer.ChildObjects.Clear();

            footer = section.HeadersFooters[HeaderFooterType.FooterOdd];
            if (footer != null)
                footer.ChildObjects.Clear();

            footer = section.HeadersFooters[HeaderFooterType.FooterEven];
            if (footer != null)
                footer.ChildObjects.Clear();
                              
        }
        
        doc.SaveToFile("Result.docx", FileFormat.Docx2013);


    }

With the help of Spire.Doc, we can easily add and remove header on the word documents in C#. This article we will demonstrate how to lock down the header information from editing. We will divide it into two parts for the demo. Once is for locking the header information on the existing word document with header and the other is on the new creating word document.

How to lock the header information on the existing word document.

//Load the sample document with header
Document doc = new Document();
doc.LoadFromFile("sample.docx");

//Get the first section from the word document
Section section = doc.Sections[0];

//Protect the document and set the ProtectionType as AllowOnlyFormFields
doc.Protect(ProtectionType.AllowOnlyFormFields, "123");

//Set the ProtectForm as false to unprotect the section
section.ProtectForm = false;

//Save the document to file
doc.SaveToFile("Result.docx", FileFormat.Docx2013);

Effective screenshot of the header has been locked and the other area can be edited:

How to lock the header from editing on word document in C#

How to lock the header information for the new word document.

//Create a new instance of word document
Document doc = new Document();

//Add a section to the word document
Section section = doc.AddSection();

//Add header information to the section
HeaderFooter header = section.HeadersFooters.Header;
Paragraph HParagraph = header.AddParagraph();
TextRange HText = HParagraph.AppendText("Protect header");

//Add a paragraph to the section
Paragraph Para = section.AddParagraph();
Para.AppendText("Demo of how to lock the header information by Spire.Doc ");

//Set the ProtectionType as AllowOnlyFormFields and then unprotect the section
doc.Protect(ProtectionType.AllowOnlyFormFields, "123");
section.ProtectForm = false;

//Save the document to file
doc.SaveToFile("Result.docx", FileFormat.Docx2013);

How to lock the header from editing on word document in C#

When you create several Word documents that are closely related, you may want the header or footer of one document to be used as the header or footer of other documents. For example, you're creating internal documents with your company logo or name or other material been placed in header, you only have to create the header once and copy the header to other places.

In this article, I'll introduce you a simple and efficient solution to copy the entire header (including text and graphic) from one Word document and insert it to another.

Source Document:

Copy Header/Footer between Word Documents in C#, VB.NET

Detail Steps:

Step 1: Create a new instance of Document class and load the source file.

Document doc1 = new Document();
doc1.LoadFromFile("test1.docx");

Step 2: Get the header section from the source document.

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

Step 3: Initialize a new instance of Document and load another file that you want to insert header.

Document doc2 = new Document("test2.docx");

Step 4: Call DocuentObject.Clone() method to copy each object in the header of source file, then call DocumentObjectCollection.Add() method to insert copied object into the header of destination file.

foreach (Section section in doc2.Sections)
{
    foreach (DocumentObject obj in header.ChildObjects)
    {
        section.HeadersFooters.Header.ChildObjects.Add(obj.Clone());
    }
}

Step 5: Save the changes and launch the file.

doc2.SaveToFile("test2.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("test2.docx");

Destination Document:

Copy Header/Footer between Word Documents in C#, VB.NET

Full Code:

[C#]
Document doc1 = new Document();
doc1.LoadFromFile("test1.docx");
HeaderFooter header = doc1.Sections[0].HeadersFooters.Header;
Document doc2 = new Document("test2.docx");
foreach (Section section in doc2.Sections)
{
    foreach (DocumentObject obj in header.ChildObjects)
    {
        section.HeadersFooters.Header.ChildObjects.Add(obj.Clone());
    }
}
doc2.SaveToFile("test2.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("test2.docx");
[VB.NET]
Dim doc1 As New Document()
doc1.LoadFromFile("test1.docx")
Dim header As HeaderFooter = doc1.Sections(0).HeadersFooters.Header
Dim doc2 As New Document("test2.docx")
For Each section As Section In doc2.Sections
	For Each obj As DocumentObject In header.ChildObjects
		section.HeadersFooters.Header.ChildObjects.Add(obj.Clone())
	Next
Next
doc2.SaveToFile("test2.docx", FileFormat.Docx2013)
System.Diagnostics.Process.Start("test2.docx")

In MS Word page border options, there are checkboxes to choose whether page border surrounds header/footer or not. This feature is very important for which can be used to manage the positional relation between page border and header/footer. Spire.Doc supports to set the two frequently-used features: page border and header/footer, and it supports to manage their spatial relations, too. This article is going to introduce the method to set whether page border surrounds header/footer or not.

Note: before start, please download the latest version of Spire.Doc and add the .dll in the bin folder as the reference of Visual Studio.

Step 1: Create a Word document and add a section.

            Document document = new Document();
            Section section = document.AddSection();

Step 2: Add a sample page border to the document using Spire.Doc library.

            section.PageSetup.Borders.BorderType = BorderStyle.Wave;
            section.PageSetup.Borders.Color = Color.Green;
            section.PageSetup.Borders.Left.Space = 20;
            section.PageSetup.Borders.Right.Space = 20;

Step 3: Add sample header and footer to the document using Spire.Doc library.

            //add a header and set its format
            Paragraph paragraph1 = section.HeadersFooters.Header.AddParagraph();
            paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Right;
            TextRange headerText = paragraph1.AppendText("Header isn't included in page border");
            headerText.CharacterFormat.FontName = "Calibri";
            headerText.CharacterFormat.FontSize = 20;
            headerText.CharacterFormat.Bold = true;

            //add a footer and set its format
            Paragraph paragraph2 = section.HeadersFooters.Footer.AddParagraph();
            paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left;
            TextRange footerText = paragraph2.AppendText("Footer is included in page border");
            footerText.CharacterFormat.FontName = "Calibri";
            footerText.CharacterFormat.FontSize = 20;
            footerText.CharacterFormat.Bold = true;

Step 4: Set the header not included in the page border while the footer included.

            section.PageSetup.PageBorderIncludeHeader = false;
            section.PageSetup.HeaderDistance = 40;
            section.PageSetup.PageBorderIncludeFooter = true;
            section.PageSetup.FooterDistance = 40;

Step 5: Save the document and launch to see effect.

            document.SaveToFile("result.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("result.docx"); 

Effects:

How to set whether page border surrounds header/footer or not

Full Codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace Mirror_Margin
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            Section section = document.AddSection();

            section.PageSetup.Borders.BorderType = BorderStyle.Wave;
            section.PageSetup.Borders.Color = Color.Green;
            section.PageSetup.Borders.Left.Space = 20;
            section.PageSetup.Borders.Right.Space = 20;
            
            Paragraph paragraph1 = section.HeadersFooters.Header.AddParagraph();
            paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Right;
            TextRange headerText = paragraph1.AppendText("Header isn't included in page border");
            headerText.CharacterFormat.FontName = "Calibri";
            headerText.CharacterFormat.FontSize = 20;
            headerText.CharacterFormat.Bold = true;

            Paragraph paragraph2 = section.HeadersFooters.Footer.AddParagraph();
            paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Left;
            TextRange footerText = paragraph2.AppendText("Footer is included in page border");
            footerText.CharacterFormat.FontName = "Calibri";
            footerText.CharacterFormat.FontSize = 20;
            footerText.CharacterFormat.Bold = true;

            section.PageSetup.PageBorderIncludeHeader = false;
            section.PageSetup.HeaderDistance = 40;
            section.PageSetup.PageBorderIncludeFooter = true;
            section.PageSetup.FooterDistance = 40;

            document.SaveToFile("result.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("result.docx"); 
        }
    }
}

In the MS Word Header & Footer Tools options, we could choose "Different First Page" and "Different odd and even pages". The article "How to create different headers/footers for odd and even pages" introduces the method to set different odd and even pages using Spire.Doc. Spire.DOC also provides an easy and quick method to add different first page header & footer. This article is going to introduce the method to add different first page header & footer.

FYI, if you only need the first page header and footer, please just set the first page header & footer and leave the rest alone. In this way, your Word document will only have header & footer in the first page, which provides a simpler way to add a header only into the first page of a document than the method mentioned in the article "How to add a header only into the first page of a document".

Note: before start, please download the latest version of Spire.Doc and add Spire.Doc .dll in the bin folder as the reference of Visual Studio.

Step 1: Load the sample document that only contains text.

Document document = new Document();
document.LoadFromFile("T.docx");

Step 2: Get the section and set the property true.

Section section = document.Sections[0];
section.PageSetup.DifferentFirstPageHeaderFooter = true;

Step 3: Set the first page header. Here we append a picture as the header.

Paragraph paragraph1 = section.HeadersFooters.FirstPageHeader.AddParagraph();
paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Right;           
DocPicture headerimage = paragraph1.AppendPicture(Image.FromFile("2.bmp"));

Step 4: Set the first page footer.

Paragraph paragraph2 = section.HeadersFooters.FirstPageFooter.AddParagraph();
paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Center;
TextRange FF = paragraph2.AppendText("First Page Footer");
FF.CharacterFormat.FontSize = 20;

Step 5: Set the other header & footer. If you only need the first page header & footer, don't set this.

Paragraph paragraph3 = section.HeadersFooters.Header.AddParagraph();
paragraph3.Format.HorizontalAlignment = HorizontalAlignment.Center;
TextRange NH = paragraph3.AppendText("If you only need first page header, don't set this.");
NH.CharacterFormat.FontSize = 20;

Paragraph paragraph4 = section.HeadersFooters.Footer.AddParagraph();
paragraph4.Format.HorizontalAlignment = HorizontalAlignment.Center;
TextRange NF = paragraph4.AppendText("If you only need first page footer, don't set this.");
NF.CharacterFormat.FontSize = 20;

Step 6: save the document and launch to see effects.

document.SaveToFile("R.docx", FileFormat.Docx2010);
System.Diagnostics.Process.Start("R.docx");

Effects:

How to add different first page header & footer

How to add different first page header & footer

Full codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace Mirror_Margin
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("T.docx");

            Section section = document.Sections[0];
            section.PageSetup.DifferentFirstPageHeaderFooter = true;

            Paragraph paragraph1 = section.HeadersFooters.FirstPageHeader.AddParagraph();
            paragraph1.Format.HorizontalAlignment = HorizontalAlignment.Right;           
            DocPicture headerimage = paragraph1.AppendPicture(Image.FromFile("2.bmp"));

            Paragraph paragraph2 = section.HeadersFooters.FirstPageFooter.AddParagraph();
            paragraph2.Format.HorizontalAlignment = HorizontalAlignment.Center;            
            TextRange FF = paragraph2.AppendText("First Page Footer");
            FF.CharacterFormat.FontSize = 20;

            Paragraph paragraph3 = section.HeadersFooters.Header.AddParagraph();
            paragraph3.Format.HorizontalAlignment = HorizontalAlignment.Center;
            TextRange NH = paragraph3.AppendText("If you only need first page header, don't set this.");
            NH.CharacterFormat.FontSize = 20;

            Paragraph paragraph4 = section.HeadersFooters.Footer.AddParagraph();
            paragraph4.Format.HorizontalAlignment = HorizontalAlignment.Center;
            TextRange NF = paragraph4.AppendText("If you only need first page footer, don't set this.");
            NF.CharacterFormat.FontSize = 20;
           
            document.SaveToFile("R.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("R.docx");
        }
    }
}

Headers and footers are widely used to show addition information such as chapter name, page numbers to keep the document organized. By default, MS Word sets the same headers and footers on each page, but sometimes we need to create different headers or footers for odd and even pages. This article is going to introduce the method to set different odd and even header/footer using Spire.Doc in C#.

Note: Before Start, please download the latest version of Spire.Doc and add Spire.Doc .dll in the bin folder as the reference of Visual Studio.

Step 1: Create a new document and load from file.

Document document = new Document();
document.LoadFromFile("T1.docx"); 

Step 2: Add a section and set the property true.

Section section = document.Sections[0];
section.PageSetup.DifferentOddAndEvenPagesHeaderFooter = true;

Step 3: Create odd and even footer, odd and even header, and set their format.

//add EvenFooter
Paragraph P1 = section.HeadersFooters.EvenFooter.AddParagraph();
TextRange EF = P1.AppendText("Even Footer Demo from E-iceblue Using Spire.Doc");
EF.CharacterFormat.FontName = "Calibri";
EF.CharacterFormat.FontSize = 20;
EF.CharacterFormat.TextColor = Color.Green;
EF.CharacterFormat.Bold = true;
P1.Format.HorizontalAlignment = HorizontalAlignment.Center;
           
//add OddFooter
Paragraph P2 = section.HeadersFooters.OddFooter.AddParagraph();
TextRange OF = P2.AppendText("Odd Footer Demo");
P2.Format.HorizontalAlignment = HorizontalAlignment.Center;
OF.CharacterFormat.FontName = "Calibri";
OF.CharacterFormat.FontSize = 20;
OF.CharacterFormat.Bold = true;
OF.CharacterFormat.TextColor = Color.Blue;

//add OddHeader
Paragraph P3 = section.HeadersFooters.OddHeader.AddParagraph();
TextRange OH = P3.AppendText("Odd Header Demo");
P3.Format.HorizontalAlignment = HorizontalAlignment.Center;
OH.CharacterFormat.FontName = "Calibri";
OH.CharacterFormat.FontSize = 20;
OH.CharacterFormat.Bold = true;
OH.CharacterFormat.TextColor = Color.Blue;

//add EvenHeader
Paragraph P4 = section.HeadersFooters.EvenHeader.AddParagraph();
TextRange EH = P4.AppendText("Even Header Demo from E-iceblue Using Spire.Doc");
P4.Format.HorizontalAlignment = HorizontalAlignment.Center;
EH.CharacterFormat.FontName = "Calibri";
EH.CharacterFormat.FontSize = 20;
EH.CharacterFormat.Bold = true;
EH.CharacterFormat.TextColor = Color.Green;

Step 4: Save the document and launch to see effects.

document.SaveToFile("R.docx", FileFormat.Docx2010);
System.Diagnostics.Process.Start("R.docx");

Effects:

How to create different headers or footers for odd and even pages

Full code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace Mirror_Margin
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("T1.docx");
            Section section = document.Sections[0];

            section.PageSetup.DifferentOddAndEvenPagesHeaderFooter = true;

            Paragraph P1 = section.HeadersFooters.EvenFooter.AddParagraph();
            TextRange EF = P1.AppendText("Even Footer Demo from E-iceblue Using Spire.Doc");
            EF.CharacterFormat.FontName = "Calibri";
            EF.CharacterFormat.FontSize = 20;
            EF.CharacterFormat.TextColor = Color.Green;
            EF.CharacterFormat.Bold = true;
            P1.Format.HorizontalAlignment = HorizontalAlignment.Center;
           

            Paragraph P2 = section.HeadersFooters.OddFooter.AddParagraph();
            TextRange OF = P2.AppendText("Odd Footer Demo");
            P2.Format.HorizontalAlignment = HorizontalAlignment.Center;
            OF.CharacterFormat.FontName = "Calibri";
            OF.CharacterFormat.FontSize = 20;
            OF.CharacterFormat.Bold = true;
            OF.CharacterFormat.TextColor = Color.Blue;

            Paragraph P3 = section.HeadersFooters.OddHeader.AddParagraph();
            TextRange OH = P3.AppendText("Odd Header Demo");
            P3.Format.HorizontalAlignment = HorizontalAlignment.Center;
            OH.CharacterFormat.FontName = "Calibri";
            OH.CharacterFormat.FontSize = 20;
            OH.CharacterFormat.Bold = true;
            OH.CharacterFormat.TextColor = Color.Blue;

            Paragraph P4 = section.HeadersFooters.EvenHeader.AddParagraph();
            TextRange EH = P4.AppendText("Even Header Demo from E-iceblue Using Spire.Doc");
            P4.Format.HorizontalAlignment = HorizontalAlignment.Center;
            EH.CharacterFormat.FontName = "Calibri";
            EH.CharacterFormat.FontSize = 20;
            EH.CharacterFormat.Bold = true;
            EH.CharacterFormat.TextColor = Color.Green;

            document.SaveToFile("R.docx", FileFormat.Docx2010);
            System.Diagnostics.Process.Start("R.docx");
        }
    }
}

Adding page numbers to your Word documents can enhance their organization and readability. Page numbers provide a convenient reference point for readers and make it easier to navigate through lengthy documents. Whether you're working on a report, thesis, or any other document, incorporating page numbers is a simple yet effective way to improve its overall structure and accessibility.

In this article, you will learn how to add page numbers to a Word document in C# by using the Spire.Doc for .NET library.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Add Page Numbers to a Word Document in C#

To achieve the dynamic addition of page numbers to a Word document, Spire.Doc for .NET offers a range of fields, including FieldPage, FieldNumPages, and FieldSectionPages. These fields act as placeholders for the current page number, total page count, and section page count, allowing you to customize and automate the display of page numbers in your document.

To incorporate these placeholders (usually in the header or footer section) within your Word document, you can utilize the Paragraph.AppendField() method.

The following steps outline how to add a FieldPage field and a FieldNumPages field in the footer, resulting in the display of "X/Y" format in the document.

  • Create a Document object.
  • Load a Word document from a specified file path.
  • Get the first section using Document.Sections[index] property
  • Get the footer of the first section using Section.HeadersFooters.Footer property.
  • Add a paragraph to the footer using HeaderFooter.AddParagraph() method.
  • Insert a FieldPage field, a FieldNumPages field and a "/" to the paragraph using Paragraph.AppendField() and Parargph.AppendText() methods.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace AddPageNumbersToDocument
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Load a Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Privacy Policy.docx");

            // Get the first section
            Section section = document.Sections[0];

            // Get the footer of the section
            HeaderFooter footer = section.HeadersFooters.Footer;

            // Add "page number / page count" to the footer
            Paragraph footerParagraph = footer.AddParagraph();
            footerParagraph.AppendField("page number", FieldType.FieldPage);
            footerParagraph.AppendText(" / ");
            footerParagraph.AppendField("page count", FieldType.FieldNumPages);
            footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;

            // Apply formatting to the page number
            ParagraphStyle style = new ParagraphStyle(document);
            style.CharacterFormat.Bold = true;
            style.CharacterFormat.FontName = "Times New Roman";
            style.CharacterFormat.FontSize = 18;
            style.CharacterFormat.TextColor = Color.Red;
            document.Styles.Add(style);
            footerParagraph.ApplyStyle(style);

            // Save the document
            document.SaveToFile("AddPageNumbersToDocument.docx");

            // Dispose resources
            document.Dispose();
        }
    }
}

C#: Add Page Numbers to a Word Document

Add Page Numbers to a Specific Section in a Word Document in C#

By default, page numbers in the footer of a section are automatically linked to the previous section, ensuring a continuous display. However, if you wish to add page numbers to a specific section only, you need to unlink the subsequent section from the previous section and remove the content of the footers in the subsequent sections.

The following are the steps to add page numbers to a specific section in a Word document using Spire.Doc for .NET.

  • Create a Document object.
  • Load a Word document from a specified file path.
  • Get a specific section using Document.Sections[index] property
  • Get the footer of the section using Section.HeadersFooters.Footer property.
  • Restart page numbering from 1 by setting Section.PageSetup.RestartPageNumbering property to true and Section.PageSetup.PageStartingNumber property to 1.
  • Insert a FieldPage field, a FieldSectionPages field and a "/" to the footer using Paragraph.AppendField() and Parargph.AppendText() methods.
  • Disable "Link to previous" by setting HeadersFooters.Footer.LinkToPrevious propety to false.
  • Delete the content of the footers in the subsequent sections
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace AddPageNumbersToSpecificSection
{ 
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Load a Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Privacy Policy.docx");

            // Get a specific section
            int sectionIndex = 1;
            Section section = document.Sections[sectionIndex];

            // Restart page numbering from 1
            section.PageSetup.RestartPageNumbering = true;
            section.PageSetup.PageStartingNumber = 1;

            // Get the footer of the section
            HeaderFooter footer = section.HeadersFooters.Footer;

            // Add "page number / page count" to the footer
            Paragraph footerParagraph = footer.AddParagraph();
            footerParagraph.AppendField("page number", FieldType.FieldPage);
            footerParagraph.AppendText(" / ");
            footerParagraph.AppendField("page count", FieldType.FieldSectionPages);
            footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;

            // Apply formatting to the page number
            ParagraphStyle style = new ParagraphStyle(document);
            style.CharacterFormat.Bold = true;
            style.CharacterFormat.FontName = "Times New Roman";
            style.CharacterFormat.FontSize = 18;
            style.CharacterFormat.TextColor = Color.Red;
            document.Styles.Add(style);
            footerParagraph.ApplyStyle(style);

            // Disable "Link to previous" in the subsequent section
            document.Sections[sectionIndex + 1].HeadersFooters.Footer.LinkToPrevious = false;

            // Delete the content of the footers in the subsequent sections
            for (int i = sectionIndex + 1; i < document.Sections.Count; i++)
            {
                document.Sections[i].HeadersFooters.Footer.ChildObjects.Clear();
                document.Sections[i].HeadersFooters.Footer.AddParagraph();
            }

            // Save the document
            document.SaveToFile("AddPageNumbersToSection.docx");

            // Dispose resources
            document.Dispose();
        }
    }
}

C#: Add Page Numbers to a Word Document

Add Different Page Numbers to Different Sections in a Word Document in C#

To ensure that different sections have distinct page numbers, you need to get each section in the document, add page numbers to them separately, and restart page numbering from 1 at the beginning of each section.

The following are detailed steps.

  • Create a Document object.
  • Load a Word document from a specified file path.
  • Iterate through the sections in the document.
    • Get a specific section using Document.Sections[index] property
    • Get the footer of the section using Section.HeadersFooters.Footer property.
    • Restart page numbering from 1 by setting Section.PageSetup.RestartPageNumbering property to true and Section.PageSetup.PageStartingNumber property to 1.
    • Insert a FieldPage field, a FieldSectionPages field and a "/" to the footer using Paragraph.AppendField() and Parargph.AppendText() methods.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;

namespace AddDifferentPageNumbersToDifferentSections
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document document = new Document();

            // Load a Word file
            document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Privacy Policy.docx");

            // Iterate through the sections in the document
            for (int i = 0; i < document.Sections.Count; i++)
            {
                // Get a specific section
                Section section = document.Sections[i];

                // Restart page numbering from 1
                section.PageSetup.RestartPageNumbering = true;
                section.PageSetup.PageStartingNumber = 1;

                // Get the footer of the section
                HeaderFooter footer = section.HeadersFooters.Footer;

                // Add "page number / page count" to the footer
                Paragraph footerParagraph = footer.AddParagraph();
                footerParagraph.AppendField("page number", FieldType.FieldPage);
                footerParagraph.AppendText(" / ");
                footerParagraph.AppendField("page count", FieldType.FieldSectionPages);
                footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;

                // Apply formatting to the page number
                ParagraphStyle style = new ParagraphStyle(document);
                style.CharacterFormat.Bold = true;
                style.CharacterFormat.FontName = "Times New Roman";
                style.CharacterFormat.FontSize = 18;
                style.CharacterFormat.TextColor = Color.Red;
                document.Styles.Add(style);
                footerParagraph.ApplyStyle(style);
            }

            // Save the document
            document.SaveToFile("AddDifferentPageNumbersToSections.docx");

            // Dispose resources
            document.Dispose();
        }
    }
}

C#: Add Page Numbers to a Word Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Spire.Doc for .NET enables developers to add, modify and remove text and Image header for word documents easily. We have already shown you how to insert header for all the pages and only add header for the first page in word document in C#. This article will focus on demonstrate how to remove the header for all the pages in word document and only remove the header for the first page in C#.

In the example, we will load a word document with headers. And then we will show you how to remove the header only from the first page and all the pages independently.

Check the word document with headers:

How to remove header from the word document in C#

Step 1: Create a new document and load from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Get the first section of document.

Section section = doc.Sections[0];

Step 3: Remove the header only from the first page of word document.

//This is necessary
section.PageSetup.DifferentFirstPageHeaderFooter = true;
section.HeadersFooters.FirstPageHeader.ChildObjects.Clear();

Step 4: Remove the header for all the pages.

section.HeadersFooters.Header.ChildObjects.Clear();

Step 5: Save the document to file.

doc.SaveToFile("output.docx", FileFormat.Docx);

Effective screenshot of the removal of the header:

How to remove header from the word document in C#

Full codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using System.Drawing;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace RemoveHeader
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Blues.docx");
            Section section = doc.Sections[0];
            //This is necessary
            section.PageSetup.DifferentFirstPageHeaderFooter = true;
            section.HeadersFooters.FirstPageHeader.ChildObjects.Clear();
            //section.HeadersFooters.Header.ChildObjects.Clear();
            doc.SaveToFile("output.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("output.docx");
        }
    }
}

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

page