Add page numbers in different sections in Word document via Spire.Doc

Sometimes in one Word document developers need to add page numbers for different sections, for example cover, directory and content are in different sections. This article talks about how to add page numbers for different sections via Spire.Doc.

Here will import a test document within 3 sections inside as followed screenshot.

Add page numbers in different sections in Word document via Spire.Doc

Here are the detailed steps:

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

Document document = new Document("test.docx");

Step 2: Create footer for the first section and add page number inside.

HeaderFooter footer = document.Sections[0].HeadersFooters.Footer;
Paragraph footerParagraph = footer.AddParagraph();
footerParagraph.AppendField("page number", FieldType.FieldPage);
footerParagraph.AppendText(" of ");
footerParagraph.AppendField("number of pages", FieldType.FieldSectionPages);
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;

Step 3: Restart page number of next section and set the starting page number to 1.

document.Sections[1].PageSetup.RestartPageNumbering = true;
document.Sections[1].PageSetup.PageStartingNumber = 1;

Step 4: Repeat step2 and Step3 for the rest sections, so change the code with for loop.

for (int i = 0; i < 3; i++)
            {
                HeaderFooter footer = document.Sections[i].HeadersFooters.Footer;
                Paragraph footerParagraph = footer.AddParagraph();
                footerParagraph.AppendField("page number", FieldType.FieldPage);
                footerParagraph.AppendText(" of ");
                footerParagraph.AppendField("number of pages", FieldType.FieldSectionPages);
                footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;

                if (i == 2)
                    break;
                else
                {
                    document.Sections[i + 1].PageSetup.RestartPageNumbering = true;
                    document.Sections[i + 1].PageSetup.PageStartingNumber = 1;
                }
            }

Step 5: Save and review.

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

Result screenshot:

Add page numbers in different sections in Word document via Spire.Doc