Apache PDFBox Add Watermark to PDF Document
This tutorial demonstrates how to add a watermark to a PDF document in Java using Apache PDFBox.
Maven Dependencies
We use Apache Maven to manage our project dependencies. Make sure the following dependencies reside on the class-path.
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.8</version>
</dependency>
Apache PDFBox Add Watermark to PDF Document
In this example we add a watermark to an existing PDF document. We use the Overlay
class to create an overlay in the background. Finally we save the PDF document.
package com.memorynotfound.pdf.pdfbox;
import org.apache.pdfbox.multipdf.Overlay;
import org.apache.pdfbox.pdmodel.PDDocument;
import java.io.File;
import java.util.HashMap;
public class Watermark {
public static void main(String[] args) throws Exception{
PDDocument realDoc = PDDocument.load(new File("/tmp/example.pdf"));
HashMap<Integer, String> overlayGuide = new HashMap<Integer, String>();
for(int i=0; i<realDoc.getNumberOfPages(); i++){
overlayGuide.put(i+1, "/tmp/watermark.pdf");
}
Overlay overlay = new Overlay();
overlay.setInputPDF(realDoc);
overlay.setOverlayPosition(Overlay.Position.BACKGROUND);
overlay.overlay(overlayGuide);
realDoc.save(new File("/tmp/watermarked.pdf"));
}
}
Demo
When we execute the application, the watermark is applied to the PDF document. You can view the result here. Minor note, for a watermark you should probably be using an image or text with transparent colours.
how can we add the watermark to image within pdf