How to add watermark in PDF document using java iText library

In this tutorial you will learn how to add the watermark text in existing PDF document using iText java library.

Please note we are using the iText version 5 for this example.

You have to follow these steps in order to add watermark in PDF document.

First get the PdfContentByte object by pdfStamper object.

PdfContentByte underContent = pdfStamper.getUnderContent(1);

Second get the BaseFont of watermark text.

BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);

Third add text content as watermark in as shown below.

underContent.showTextAligned(Element.ALIGN_CENTER, “www.java-connect.com”, 300, 700, 0);

Below example of code shows how to add the watermark string in existing PDF document.

package com.java.connect.itext;
 
import java.awt.Color;
import java.io.FileOutputStream;
import java.io.IOException;
 
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfGState;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
 
public class PDFWatermarkExample {
    public static void main(String[] args) throws IOException, DocumentException {
        // Read the existing PDF document
        PdfReader pdfReader = new PdfReader("PDF_Hello_World_Example.pdf");
        // Get the PdfStamper object
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("PDF_Hello_World_Watermark_Example.pdf"));
        // Get the PdfContentByte type by pdfStamper.
        PdfContentByte underContent = pdfStamper.getUnderContent(1);
 
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED);
        PdfGState gs = new PdfGState();
        gs.setFillOpacity(0.8f);
        underContent.setGState(gs);
        underContent.beginText();
        underContent.setFontAndSize(bf, 20);
        underContent.setColorFill(Color.LIGHT_GRAY);
        underContent.showTextAligned(Element.ALIGN_CENTER, "www.java-connect.com", 300, 700, 0);
        underContent.endText();
 
        pdfStamper.close();
 
    }
}

The modified PDF document looks like below screen.

iText-add-watermark-in-PDF-document-using-java-iText-library_files