AddPageNumbersToExistingPageNumberPDF.java Source code

Java tutorial

Introduction

Here is the source code for AddPageNumbersToExistingPageNumberPDF.java

Source

import java.io.FileOutputStream;

import com.lowagie.text.Element;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;

public class AddPageNumbersToExistingPageNumberPDF {
    public static void main(String[] args) {
        try {
            PdfReader reader = new PdfReader("YourOwnPDF.pdf");
            int n = reader.getNumberOfPages();

            PdfStamper stamp = new PdfStamper(reader,
                    new FileOutputStream("AddPageNumbersToExistingPageNumberPDF.pdf"));

            int i = 0;

            PdfContentByte over;
            BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
            while (i < n) {
                i++;
                over = stamp.getOverContent(i);
                over.beginText();
                over.setFontAndSize(bf, 18);
                over.setTextMatrix(30, 30);
                over.showText("page " + i);
                over.setFontAndSize(bf, 32);
                over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
                over.endText();
            }
            stamp.close();
        } catch (Exception de) {
            de.printStackTrace();
        }
    }
}