DEV Community

jelizaveta
jelizaveta

Posted on

Adding Page Numbers to PDF with Python (Full Tutorial)

When working with PDFs such as contracts, reports, academic papers, and technical documents, adding page numbers is almost an essential requirement. Traditional PDF editing often relies on complex layout tools; however, with Free Spire.PDF for Python, you can use simple code to add page numbers to the PDF footer in center, left, or right alignment .

This article will teach you how to use the powerful Spire.PDF for Python library to automatically add page numbers to PDF files. We provide complete code for three styles: centered, left-aligned, and right-aligned, so you can choose flexibly based on your needs.

1. Preparation

First, install the Spire.PDF for Python library:

pip install spire.pdf
Enter fullscreen mode Exit fullscreen mode

After installation, import the required modules in your Python code:

from spire.pdf.common import *
from spire.pdf import *
Enter fullscreen mode Exit fullscreen mode

2. Key Concepts Explained

Before writing code, let’s understand the purpose of several key classes in this library:

Class Name Purpose
PdfDocument Represents a PDF document, used to load, save, and modify files
PdfPageNumberField Represents the current page number, filled automatically
PdfPageCountField Represents the total page count, filled automatically
PdfCompositeField Combines multiple fields into a formatted string
PdfTrueTypeFont Creates a TrueType font with full English support

Simply put: PdfPageNumberField and PdfPageCountField are dynamic values, and PdfCompositeField places them into a text template.

3. Complete Code Example (Centered Page Numbers)

Below is the full code to add centered English page numbers to a PDF with clean comments:

from spire.pdf.common import *
from spire.pdf import *

# Load the PDF document
doc = PdfDocument()
doc.LoadFromFile("Input.pdf")

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

# Create page number and total page fields
pageNumberField = PdfPageNumberField()
pageCountField = PdfPageCountField()

# Create English page number format: Page X of Y
compositeField = PdfCompositeField(
    font,
    brush,
    "Page {0} of {1}",
    [pageNumberField, pageCountField]
)

# Set margins (unit: points, 1 point = 1/72 inch)
leftMargin = 54.0
rightMargin = 54.0
bottomMargin = 72.0

# Loop through all pages and add page numbers
for i in range(doc.Pages.Count):
    page = doc.Pages.get_Item(i)
    pageSize = page.Size

    # Draw a separator line
    lineY = pageSize.Height - bottomMargin + 25.0
    page.Canvas.DrawLine(pen, leftMargin, lineY, pageSize.Width - rightMargin, lineY)

    # Measure text size for accurate centering
    pageNumberSize = font.MeasureString(f"Page {i + 1} of {doc.Pages.Count}")

    # Set centered position
    compositeField.Location = PointF(
        (pageSize.Width - pageNumberSize.Width) / 2,
        pageSize.Height - bottomMargin + 30.0
    )

    # Draw page number on the canvas
    compositeField.Draw(page.Canvas, 0.0, 0.0)

# Save the output file and release resources
doc.SaveToFile("Output.pdf")
doc.Dispose()
Enter fullscreen mode Exit fullscreen mode

4. Left and Right Alignment

To switch alignment, simply modify the X coordinate of compositeField.Location.

4.1 Left-Aligned Page Numbers

# Left alignment: X = left margin
compositeField.Location = PointF(
    leftMargin,
    pageSize.Height - bottomMargin + 30.0
)
Enter fullscreen mode Exit fullscreen mode

Result: "Page 1 of 10" appears at the bottom left .

4.2 Right-Aligned Page Numbers

# Right alignment: X = page width - text width - right margin
compositeField.Location = PointF(
    pageSize.Width - pageNumberSize.Width - rightMargin,
    pageSize.Height - bottomMargin + 30.0
)
Enter fullscreen mode Exit fullscreen mode

Result: "Page 1 of 10" appears at the bottom right .

5. More English Page Number Styles

In addition to "Page X of Y", you can use these common styles:

5.1 Simple Style

compositeField = PdfCompositeField(
    font, brush, "{0} / {1}", 
    [pageNumberField, pageCountField]
)
# Output: 1 / 10
Enter fullscreen mode Exit fullscreen mode

5.2 With Decorators

compositeField = PdfCompositeField(
    font, brush, "- {0} / {1} -", 
    [pageNumberField, pageCountField]
)
# Output: - 1 / 10 -
Enter fullscreen mode Exit fullscreen mode

5.3 Page Number Only

compositeField = PdfCompositeField(
    font, brush, "{0}", 
    [pageNumberField]
)
# Output: 1
Enter fullscreen mode Exit fullscreen mode

6. Recommended Fonts for English

Font Name Description Usage
Times New Roman Formal, standard Papers, reports
Arial Clean, modern Business, web
Calibri Smooth, readable Office documents

Example:

font = PdfTrueTypeFont("Arial", 12.0, PdfFontStyle.Regular, True)
Enter fullscreen mode Exit fullscreen mode

7. Parameter Tuning Guide

7.1 Margin Adjustment

leftMargin = 54.0      # Increase → move right (left-aligned)
rightMargin = 54.0     # Increase → move left (right-aligned)
bottomMargin = 72.0    # Increase → move up; decrease → move down
Enter fullscreen mode Exit fullscreen mode

7.2 Vertical Position Adjustment

# Separator line position
lineY = pageSize.Height - bottomMargin + 15.0

# Page number vertical position
compositeField.Location = PointF(x, pageSize.Height - bottomMargin + 18.0)
Enter fullscreen mode Exit fullscreen mode
  • Increase values → move down
  • Decrease values → move up

7.3 Font Size

# Change to 14pt
font = PdfTrueTypeFont("Times New Roman", 14.0, PdfFontStyle.Regular, True)
Enter fullscreen mode Exit fullscreen mode

8. Common Issues & Solutions

Q1: Text displays incorrectly?

A: Use standard English fonts: Times New Roman, Arial, Calibri.

Q2: Page numbers appear in header instead of footer?

A: Increase the Y position value to move them down.

Q3: Page numbers overlap content?

A: Increase bottomMargin to create more space.

Q4: Skip the title page?

A: Start the loop from index 1:

for i in range(1, doc.Pages.Count):
Enter fullscreen mode Exit fullscreen mode

Q5: Add page numbers only to specific pages?

A: Add a condition:

for i in range(doc.Pages.Count):
    if 2 <= i <= 10:
        # Draw page numbers here
Enter fullscreen mode Exit fullscreen mode

9. Summary

With Spire.PDF for Python, you can add professional English page numbers to PDFs in just a few lines of code. The library supports centered, left, and right alignment.

Core steps:

  1. Load the PDF
  2. Define font and fields
  3. Create the page number format
  4. Loop and draw on each page
  5. Save the document

This method is efficient, reusable, and works for documents of any size.

Top comments (0)