Java tutorial
/* * This example was written by Bruno Lowagie, author of the book * 'iText in Action' by Manning Publications (ISBN: 1932394796). * You can use this example as inspiration for your own applications. * The following license applies: * http://www.1t3xt.com/about/copyright/index.php?page=MIT */ package questions.ocg; import java.io.FileOutputStream; import java.io.IOException; import com.lowagie.text.DocumentException; import com.lowagie.text.Image; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfLayer; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfStamper; public class AddOptionalWatermark { public static final String RESOURCE = "resources/questions/pdfs/hello.pdf"; public static final String RESULT = "results/questions/ocg/watermarks.pdf"; public static final String IMAGE_PRINTED = "resources/questions/img/1t3xt.gif"; public static final String IMAGE_NOT_PRINTED = "resources/questions/img/logo.gif"; public static void main(String[] args) throws DocumentException, IOException { PdfReader reader = new PdfReader(RESOURCE); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT)); Image image1 = Image.getInstance(IMAGE_PRINTED); Image image2 = Image.getInstance(IMAGE_NOT_PRINTED); PdfLayer watermark_printed = new PdfLayer("printed", stamper.getWriter()); watermark_printed.setOn(false); watermark_printed.setOnPanel(false); watermark_printed.setPrint("print", true); PdfLayer watermark_not_printed = new PdfLayer("not_printed", stamper.getWriter()); watermark_not_printed.setOn(true); watermark_not_printed.setOnPanel(false); watermark_not_printed.setPrint("print", false); for (int i = 0; i < stamper.getReader().getNumberOfPages();) { PdfContentByte cb = stamper.getUnderContent(++i); Rectangle rectangle = stamper.getReader().getPageSizeWithRotation(i); cb.beginLayer(watermark_printed); float AbsoluteX = rectangle.getLeft() + (rectangle.getWidth() - image1.getPlainWidth()) / 2; float AbsoluteY = rectangle.getBottom() + (rectangle.getHeight() - image1.getPlainHeight()) / 2; image1.setAbsolutePosition(AbsoluteX, AbsoluteY); cb.addImage(image1); cb.endLayer(); cb.beginLayer(watermark_not_printed); AbsoluteX = rectangle.getLeft() + (rectangle.getWidth() - image2.getPlainWidth()) / 2; AbsoluteY = rectangle.getBottom() + (rectangle.getHeight() - image2.getPlainHeight()) / 2; image2.setAbsolutePosition(AbsoluteX, AbsoluteY); cb.addImage(image2); cb.endLayer(); } stamper.close(); } }