Adding Page Numbers to PDF Documents in Java

To enhence readability and oragnization of PDF files, page numbers can be programmatically added using the Free Spire.PDF for Java library.

Setup Instructions:

  1. Download and extract the Free Spire.PDF for Java package.
  2. Add Spire.Pdf.jar from the lib folder to your project’s classpath, or include it via Maven by configuring your pom.xml as shown below.

Maven Dependency Configuration:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf.free</artifactId>
        <version>2.6.3</version>
    </dependency>
</dependencies>

Implementation Code:

import com.spire.pdf.PdfDocument;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D;

public class AddPageNumbers {

    public static void main(String[] args) {
        // Load an existing PDF document
        PdfDocument document = new PdfDocument();
        document.loadFromFile("sample.pdf");

        // Define font for the page number text
        PdfTrueTypeFont textFont = new PdfTrueTypeFont(new Font("SimSun", Font.PLAIN, 10), true);

        // Get the size of the first page to determine layout
        Dimension2D pageSize = document.getPages().get(0).getSize();
        float verticalOffset = (float) pageSize.getHeight() - 40;

        // Iterate through each page
        for (int pageIndex = 0; pageIndex < document.getPages().getCount(); pageIndex++) {
            // Create fields for current page number and total page count
            PdfPageNumberField currentPage = new PdfPageNumberField();
            PdfPageCountField totalPages = new PdfPageCountField();

            // Combine them into a formatted string: "Page X of Y"
            PdfCompositeField pageNumberLabel = new PdfCompositeField(
                textFont,
                PdfBrushes.getBlack(),
                "第{0}页 共{1}页",
                currentPage,
                totalPages
            );

            // Align text to the right vertically at the top
            pageNumberLabel.setStringFormat(
                new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top)
            );

            // Measure the rendered text size
            Dimension2D labelSize = textFont.measureString(pageNumberLabel.getText());

            // Center horizontally near the bottom of the page
            float horizontalCenter = ((float) pageSize.getWidth() - (float) labelSize.getWidth()) / 2;
            pageNumberLabel.setBounds(
                new Rectangle2D.Float(horizontalCenter, verticalOffset, (float) labelSize.getWidth(), (float) labelSize.getHeight())
            );

            // Render the field onto the current page
            pageNumberLabel.draw(document.getPages().get(pageIndex).getCanvas());
        }

        // Save the modified document
        document.saveToFile("AddPageNumbers.pdf");
    }
}

Tags: java PDF Page Numbering Free Spire.PDF Document Processing

Posted on Thu, 16 Jul 2026 16:13:06 +0000 by speckledapple