Watermark can add a level of security to a PDF against content piracy. Watermarks can be added in PDF using the Overlay class provided by the PDFBox library.Lets see an example on how to add watermark in PDF using Apache PDFBox.
Important methods of the Overlay class:
1)
setInputFile(String inputFile) Sets the file to be overlayed.
2) setInputPDF(PDDocument inputPDF) Sets the PDF to be overlayed.
3) setOverlayPosition(Overlay.Position overlayPosition) Sets the overlay position.
4) overlay(Map<Integer,String> specificPageOverlayFile) This will add overlays to a documents. The map conatins page numbers and the watermark image/pdf location.
Example
We will take the following PDF file and add a watermark to it.
File without watermark
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.kscodes.examples.pdfbox; import java.io.File; import java.io.IOException; import java.util.HashMap; import org.apache.pdfbox.multipdf.Overlay; import org.apache.pdfbox.pdmodel.PDDocument; public class WatermarkExample { public static void main(String args[]) { try { // Load a existing PDF file PDDocument pdDocument = PDDocument .load(new File("K:\\Kscodes\\pdf\\pdf-sample.pdf")); // Get the pages and create a map with page number and the image to // be water marked. HashMap<Integer, String> overlayProps = new HashMap<Integer, String>(); for (int i = 0; i < pdDocument.getNumberOfPages(); i++) { overlayProps.put(i + 1, "K:\\Kscodes\\pdf\\imageSample.pdf"); } // Using the Overlay object add the map of properties to the PDF Overlay overlay = new Overlay(); overlay.setInputPDF(pdDocument); overlay.setOverlayPosition(Overlay.Position.BACKGROUND); overlay.overlay(overlayProps); // Save the PDF to a new or same location pdDocument.save("K:\\Kscodes\\pdf\\watermark-sample.pdf"); pdDocument.close(); System.out.println("PDF saved to the location !!!"); } catch (IOException ioe) { System.out.println("Error while saving pdf" + ioe.getMessage()); } } } |
Output
Reference:
1. Apache PDFBox Offical