How to add page number to an existing PDF file using itext or OpenPDF in Java Snippet

Updated: June 3, 2024

Using OpenPDF:

pom.xml
...
<dependency>
  <groupId>com.github.librepdf</groupId>
  <artifactId>openpdf</artifactId>
  <version>2.0.2</version>
</dependency>
...

Or using older version of iText

pom.xml
...
<dependency>
    <groupId>com.lowagie</groupId>
    <artifactId>itext</artifactId>
    <version>4.2.2</version>
</dependency>
...
Main.java
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfReader;


public void addPageNumber(String inputPdfPath, String outputPdfPath) {
        try (
            /// Handle Closable resources
            PdfReader pdfReader = new PdfReader(inputPdfPath);
            Document document = new Document();
            PdfCopy pdfCopy = new PdfCopy(document, new FileOutputStream(outputPdfPath))) {
            document.open();

            /// Loop through each page and add page number
            for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) {
                PdfImportedPage page = pdfCopy.getImportedPage(pdfReader, i);
                PdfCopy.PageStamp stamp = pdfCopy.createPageStamp(page);
                Phrase phrase = new Phrase("page " + i, new Font(pdf.BaseFont.createFont(), 30));
                ColumnText.showTextAligned(stamp.getOverContent(), Element.ALIGN_CENTER, phrase, page.getWidth() /2, 20, 0);
                stamp.alterContents();
                pdfCopy.addPage(page);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }