Python: Add Page Numbers to a Word Document

Adding page numbers to a Word document is a fundamental feature that enhances readability and navigation, especially in lengthy documents. It allows readers to find specific content more easily and helps authors organize their work. Word offers flexible options for adding page numbers, including choosing the location (header, footer, or body) and customizing the format and appearance to match your document's design needs.

In this article, you will learn how to add pager numbers to a Word document, as well as customizing their appearance using Spire.Doc for Python.

Install Spire.Doc for Python

This scenario requires Spire.Doc for Python and plum-dispatch v1.7.4. They can be easily installed in your Windows through the following pip command.

pip install Spire.Doc

Add Page Numbers to a Word Document in Python

To dynamically add page numbers to a Word document using Spire.Doc, you can leverage various fields such as FieldPage, FieldNumPages, and FieldSection. These fields serve as placeholders for the current page number, total page count, and section number, enabling you to customize and automate the pagination process.

You can embed these placeholders in the header or footer of your document by calling the Paragraph.AppendField() method.

Here's a step-by-step guide on how to insert a FieldPage and FieldNumPages field in the footer, which will display the page number in the format "X / Y":

  • 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, and a FieldNumPages field to the paragraph using Paragraph.AppendField() method.
  • Save the document to a different Word file.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx")

# Get the first section
section = document.Sections[0]

# Get the footer of the section
footer = section.HeadersFooters.Footer

# Add "page number / page count" to the footer
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
style = ParagraphStyle(document)
style.CharacterFormat.Bold = True
style.CharacterFormat.FontName = "Times New Roman"
style.CharacterFormat.FontSize = 18
style.CharacterFormat.TextColor = Color.get_Red()
document.Styles.Add(style)
footerParagraph.ApplyStyle(style)

# Save the document
document.SaveToFile("Output/AddPageNumbersToDocument.docx")

# Dispose resources
document.Dispose()

Python: Add Page Numbers to a Word Document

Add Page Numbers to a Specific Section in Python

By default, when you add page numbers to the footer of a section, they are automatically linked to the preceding section, maintaining a continuous sequence of page numbers. This behavior is convenient for most documents but may not be ideal when you want to start numbering from a certain section without affecting the numbering in other parts of the document.

If you need to add page numbers to a specific section without them being linked to the previous section, you must unlink the subsequent sections and clear the contents of their footers. Here's how you can do it using Spire.Doc for Python.

  • 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 and a FieldSection field to the footer using Paragraph.AppendField() method.
  • 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.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx")

# Get a specific section
sectionIndex = 1
section = document.Sections[sectionIndex]

# Restart page numbering from 1
section.PageSetup.RestartPageNumbering = True
section.PageSetup.PageStartingNumber = 1

# Get the footer of the section
footer = section.HeadersFooters.Footer

# Add "Page X, Section Y" to the footer
footerParagraph = footer.AddParagraph()
footerParagraph.AppendText("Page ")
footerParagraph.AppendField("page number", FieldType.FieldPage)
footerParagraph.AppendText(", Section ")
footerParagraph.AppendField("section number", FieldType.FieldSection)
footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center

# Apply formatting to the page number
style = ParagraphStyle(document);
style.CharacterFormat.Bold = True
style.CharacterFormat.FontName = "Times New Roman"
style.CharacterFormat.FontSize = 18
style.CharacterFormat.TextColor = Color.get_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 i in range(sectionIndex +1, document.Sections.Count, 1):     
    document.Sections[i].HeadersFooters.Footer.ChildObjects.Clear()
    document.Sections[i].HeadersFooters.Footer.AddParagraph()

# Save the document
document.SaveToFile("Output/AddPageNumbersToSection.docx")

# Dispose resources
document.Dispose()

Python: Add Page Numbers to a Word Document

Add Discontinuous Page Numbers to Different Sections in Python

When working with documents that contain multiple sections, you might want to start page numbering anew for each section to clearly distinguish between them. To achieve this, you must go through each section individually, add page numbers, and then reset the page numbering for the next section.

The following are the steps to add discontinuous page numbers to different sections using Spire.Doc for Python.

  • 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 and a FieldSection field to the footer using Paragraph.AppendField() method.
  • Save the document to a different Word file.
  • Python
from spire.doc import *
from spire.doc.common import *

# Create a Document object
document = Document()

# Load a Word file
document.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx")

# Iterate through the sections in the document
for i in range(document.Sections.Count):

    # Get a specific section
    section = document.Sections[i]

    # Restart page numbering from 1
    section.PageSetup.RestartPageNumbering = True
    section.PageSetup.PageStartingNumber = 1

    # Get the footer of the section
    footer = section.HeadersFooters.Footer

    # Add "Page X, Section Y" to the footer
    footerParagraph = footer.AddParagraph()
    footerParagraph.AppendText("Page ")
    footerParagraph.AppendField("page number", FieldType.FieldPage)
    footerParagraph.AppendText(", Section ")
    footerParagraph.AppendField("section number", FieldType.FieldSection)
    footerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center

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

# Save the document
document.SaveToFile("Output/AddDifferentPageNumbersToSections.docx")

# Dispose resources
document.Dispose()

Python: 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.