IText can modify existing PDF files. One of the most used modifications is stamping an existing PDF with text or images.
e.g. add a header, footer or watermark.
First we read the existing document using a PdfReader, then modify it using the PdfStamper.
Here is a code example:
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import java.io.FileOutputStream;
import java.io.IOException;
public class PdfStamperExample {
public static void main(String[] args) {
try {
PdfReader pdfReader = new PdfReader("HelloWorld.pdf");
PdfStamper pdfStamper = new PdfStamper(pdfReader,
new FileOutputStream("HelloWorld-Stamped.pdf"));
Image image = Image.getInstance("watermark.png");
for(int i=1; i<= pdfReader.getNumberOfPages(); i++){
PdfContentByte content = pdfStamper.getUnderContent(i);
image.setAbsolutePosition(100f, 700f);
content.addImage(image);
}
pdfStamper.close();
} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
To add content to the document we need to access to a PdfContentByte from the PdfStamper. Wecan add content either above or below the existing content in the PDF document. Here is how you obtain thePdfContentByte from the PdfStamper.
PdfContentByte underContent = pdfStamper.getUnderContent(1);
PdfContentByte overContent = pdfStamper.getOverContent(1);
The number passed as parameter is the page number of the page to get the under or over content for.
The PdfContentByte object has methods for adding all kinds of content to a PDF including text, graphics, images etc.