Add Page Numbers to an existing PDF Document using Java

In our daily work, adding page numbers to a PDF document is important since it makes the document reading, retrieval and management easier. This article will introduce a simple and free way to add page numbers to an existing PDF document at the footer space by using Free Spire.PDF for Java. You can determine where to insert page numbers according to your own requirement.

Installation
Method 1: Download the Free Spire.PDF for Java and unzip it.Then add the Spire.Pdf.jar file to your project as dependency.

Method 2: You can also add the jar dependency to maven project by adding the following configurations to the pom.xml.

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

Relevant Code Snippet:

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 a PDF document
PdfDocument doc = new PdfDocument();
doc.loadFromFile("input.pdf");

//create a true type font
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 12));

//get the page size
Dimension2D pageSize = doc.getPages().get(0).getSize();

//declare a float variable
float y = (float) pageSize.getHeight() - 72;

//loop through the pages
for (int i = 0; i < doc.getPages().getCount(); i++) {

//initialize PdfPageNumberField instance
PdfPageNumberField number = new PdfPageNumberField();

//initialize PdfPageCountField instance
PdfPageCountField count = new PdfPageCountField();

//create PdfCompositeField instance
PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.getBlack(), "Page {0} of {1}", number, count);

//set the text alignment within the composite field
compositeField.setStringFormat(new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top));

//get the text size
Dimension2D textSize = font.measureString(compositeField.getText());

//set the position and size of composite field
compositeField.setBounds(new Rectangle2D.Float((float) pageSize.getWidth() - (float) textSize.getWidth() - 80, y, (float) textSize.getWidth(), (float) textSize.getHeight()));

//draw composite filed on PDF page
compositeField.draw(doc.getPages().get(i).getCanvas());
}

//save to another file
doc.saveToFile("PageNumbers.pdf");
}
}