Python: Add Page Numbers to a PDF Document

Adding page numbers to a PDF enhances its organization and readability, making it easier for readers to navigate the document. Whether for reports, manuals, or e-books, page numbers provide a professional touch and help maintain the flow of information. This process involves determining the placement, alignment, and style of the numbers within the footer or header.

In this article, you will learn how to add page numbers to the PDF footer using Spire.PDF for Python.

Install Spire.PDF for Python

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

pip install Spire.PDF

If you are unsure how to install, please refer to this tutorial: How to Install Spire.PDF for Python on Windows

Coordinate System in PDF

When using Spire.PDF for Python to modify a PDF document, the coordinate system's origin is at the top-left corner of the page. The x-axis extends to the right, while the y-axis extends downward.

Page numbers are usually positioned in the header or footer. Thus, it's important to consider the page size and margins when determining the placement of the page numbers.

Python: Add Page Numbers to a PDF Document

Classes and Methods for Creating Page Numbers

Spire.PDF for Python provides the PdfPageNumberField and PdfPageCountField classes to retrieve the current page number and total page count. These can be merged into a single PdfCompositeField that formats the output as "Page X of Y", where X represents the current page number and Y indicates the total number of pages.

To position the PdfCompositeField on the page, use the Location property, and render it with the Draw() method.

Add Left-Aligned Page Numbers to PDF Footer

To add left-aligned page numbers in the footer, you need to consider the left and bottom page margins as well as the page height. For example, you can use coordinates such as (LeftMargin, PageHeight – BottomMargin + SmallNumber). This ensures that the page numbers align with the left side of the text while keeping a comfortable distance from both the content and the edges of the page.

The steps to add left-aligned page numbers to PDF footer are as follows:

  • Create a PdfDocument object.
  • Load a PDF file from a specified path.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to combine page count field and page number field in a single string.
  • Set the position of the composite field through PdfCompositeField.Location property to ensure the page number aligns with the left side of the text.
  • Iterate through the pages in the document, and draw the composite field on each page at the specified location.
  • Save the document to a different PDF file.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Privacy Policy.pdf")

# Create font, brush and pen
font = PdfTrueTypeFont("Times New Roman", 12.0, PdfFontStyle.Regular, True)
brush = PdfBrushes.get_Black()
pen = PdfPen(brush, 1.0)

# Create a PdfPageNumberField object and a PdfPageCountField object
pageNumberField = PdfPageNumberField()
pageCountField = PdfPageCountField()

# Create a PdfCompositeField object to combine page count field and page number field in a single string
compositeField = PdfCompositeField(font, brush, "Page {0} of {1}", [pageNumberField, pageCountField])

# Get the page size
pageSize = doc.Pages[0].Size

# Specify the blank areas around the page
leftMargin = 54.0
rightMargin = 54.0
bottomMargin = 72.0

# Set the location of the composite field
compositeField.Location = PointF(leftMargin, pageSize.Height - bottomMargin + 18.0)

# Iterate through the pages in the document
for i in range(doc.Pages.Count):

    # Get a specific page
    page = doc.Pages[i]

    # Draw a line at the specified position
    page.Canvas.DrawLine(pen, leftMargin, pageSize.Height - bottomMargin + 15.0, pageSize.Width - rightMargin, pageSize.Height - bottomMargin + 15.0)

    # Draw the composite field on the page
    compositeField.Draw(page.Canvas, 0.0, 0.0)

# Save to a different PDF file
doc.SaveToFile("Output/LeftAlignedPageNumbers.pdf")

# Dispose resources
doc.Dispose()

Python: Add Page Numbers to a PDF Document

Add Center-Aligned Page Numbers to PDF Footer

To position the page number in the center of the footer, you first need to measure the width of the page number itself. Once you have this measurement, you can calculate the appropriate X coordinate by using the formula (PageWidth - PageNumberWidth) / 2. This ensures the page number is horizontally centered within the footer.

The steps to add center-aligned page numbers to PDF footer are as follows:

  • Create a PdfDocument object.
  • Load a PDF file from a specified path.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to combine page count field and page number field in a single string.
  • Set the position of the composite field through PdfCompositeField.Location property to ensure the page number is perfectly centered in the footer.
  • Iterate through the pages in the document, and draw the composite field on each page at the specified location.
  • Save the document to a different PDF file.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Privacy Policy.pdf")

# Create font, brush and pen
font = PdfTrueTypeFont("Times New Roman", 12.0, PdfFontStyle.Regular, True)
brush = PdfBrushes.get_Black()
pen = PdfPen(brush, 1.0)

# Specify the blank margins around the page
leftMargin = 54.0
rightMargin = 54.0
bottomMargin = 72.0

# Create a PdfPageNumberField object and a PdfPageCountField object
pageNumberField = PdfPageNumberField()
pageCountField = PdfPageCountField()

# Create a PdfCompositeField object to combine page count field and page number field in a single field
compositeField = PdfCompositeField(font, brush, "Page {0} of {1}", [pageNumberField, pageCountField])

# Iterate through the pages in the document
for i in range(doc.Pages.Count):

    # Get a specific page
    page = doc.Pages[i]

    # Get the page size
    pageSize = doc.Pages[i].Size

    # Draw a line at the specified position
    page.Canvas.DrawLine(pen, leftMargin, pageSize.Height - bottomMargin + 15.0, pageSize.Width - rightMargin, pageSize.Height - bottomMargin + 15.0)

    # Measure the size the "Page X of Y"
    pageNumberSize = font.MeasureString("Page {} of {}".format(i + 1, doc.Pages.Count))

    # Set the location of the composite field
    compositeField.Location = PointF((pageSize.Width - pageNumberSize.Width)/2, pageSize.Height - bottomMargin + 18.0)

    # Draw the composite field on the page
    compositeField.Draw(page.Canvas, 0.0, 0.0)

# Save to a different PDF file
doc.SaveToFile("Output/CenterAlignedPageNumbers.pdf")

# Dispose resources
doc.Dispose()

Python: Add Page Numbers to a PDF Document

Add Right-Aligned Page Numbers to PDF Footer

To add a right-aligned page number in the footer, measure the width of the page number. Then, calculate the X coordinate using the formula PageWidth - PageNumberWidth - RightMargin. This ensures that the page number aligns with the right side of the text.

The following are the steps to add right-aligned page numbers to PDF footer:

  • Create a PdfDocument object.
  • Load a PDF file from a specified path.
  • Create a PdfPageNumberField object and a PdfPageCountField object.
  • Create a PdfCompositeField object to combine page count field and page number field in a single string.
  • Set the position of the composite field through PdfCompositeField.Location property to ensure the page number aligns with the right side of the text.
  • Iterate through the pages in the document, and draw the composite field on each page at the specified location.
  • Save the document to a different PDF file.
  • Python
from spire.pdf.common import *
from spire.pdf import *

# Create a PdfDocument object
doc = PdfDocument()

# Load a PDF file
doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Privacy Policy.pdf")

# Create font, brush and pen
font = PdfTrueTypeFont("Times New Roman", 12.0, PdfFontStyle.Regular, True)
brush = PdfBrushes.get_Black()
pen = PdfPen(brush, 1.0)

# Specify the blank margins around the page
leftMargin = 54.0
rightMargin = 54.0
bottomMargin = 72.0

# Create a PdfPageNumberField object and a PdfPageCountField object
pageNumberField = PdfPageNumberField()
pageCountField = PdfPageCountField()

# Create a PdfCompositeField object to combine page count field and page number field in a single string
compositeField = PdfCompositeField(font, brush, "Page {0} of {1}", [pageNumberField, pageCountField])

# Iterate through the pages in the document
for i in range(doc.Pages.Count):

    # Get a specific page
    page = doc.Pages[i]

    # Get the page size
    pageSize = doc.Pages[i].Size

    # Draw a line at the specified position
    page.Canvas.DrawLine(pen, leftMargin, pageSize.Height - bottomMargin + 15.0, pageSize.Width - rightMargin, pageSize.Height - bottomMargin + 15.0)

    # Measure the size the "Page X of Y"
    pageNumberSize = font.MeasureString("Page {} of {}".format(i + 1, doc.Pages.Count))

    # Set the location of the composite field
    compositeField.Location = PointF(pageSize.Width - pageNumberSize.Width - rightMargin, pageSize.Height - bottomMargin + 18.0)

    # Draw the composite field on the page
    compositeField.Draw(page.Canvas, 0.0, 0.0)

# Save to a different PDF file
doc.SaveToFile("Output/RightAlignedPageNumbers.pdf")

# Dispose resources
doc.Dispose()

Python: Add Page Numbers to a PDF 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.