Add the page number on the header/footer of a document

Page number is one of the formats of header and footer. It gives the total pages of a document and it is convenient for readers to index. Spire.Doc supports to add text and image header and footers. This tutorial will guide you how to add the page number on the header/footer of a document in C#.

Spire.Doc offers HeaderFooter class to set header or footer for word document. Then, invoke header/footer.AddParagraph() method to add header/footer paragraph and add contents by invoking paragraph.AppendText method. Here comes to the code snippet of how to add the page number for word documents.

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

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

Step 2: Create footer for the first section and add a paragraph for the footer.

HeaderFooter footer = doc.Sections[0].HeadersFooters.Footer;
Paragraph footerParagraph = footer.AddParagraph();

Step 3: Add the page number to the footer and set the alignment for the paragraph.

footerParagraph.AppendField("page number", FieldType.FieldPage);
footerParagraph.AppendText(" of ");
footerParagraph.AppendField("number of pages", FieldType.FieldNumPages);
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;

Step 4: Save the document to file.

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

Effective screenshot:

How to add the page number on the header/footer of a document

Full codes:

namespace AddPagenumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx");
            HeaderFooter footer = doc.Sections[0].HeadersFooters.Footer;
            Paragraph footerParagraph = footer.AddParagraph();
            footerParagraph.AppendField("page number", FieldType.FieldPage);
            footerParagraph.AppendText(" of ");
            footerParagraph.AppendField("number of pages", FieldType.FieldNumPages);
            footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
            doc.SaveToFile("Add.docx", FileFormat.Docx);

        }
    }
}