Add Page Numbers to an existing PDF Document using Java

<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>
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");
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store