Watermark on Document
Stamp text such as DRAFT, COPY, PAID or CONFIDENTIAL on every page of an existing PDF - one from this lab or your own upload. New documents can also get a watermark from their page setup preset (Page Setup Studio).
How it works
PdfReaderopens the existing PDF,PdfStamperwrites a copy with extra content on each page.getOverContent(page)draws on top of the text;getUnderContent(page)draws behind it (hidden by solid backgrounds such as table headers).- Transparency needs a graphics state:
PdfGState.setFillOpacity(0.2f). - The diagonal angle is
atan2(pageHeight, pageWidth), so the text runs corner to corner on any paper size.
PdfStamper stamper = new PdfStamper(new PdfReader(pdf), out);
PdfGState gs = new PdfGState();
gs.setFillOpacity(0.20f);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
PdfContentByte cb = stamper.getOverContent(i);
cb.saveState();
cb.setGState(gs);
cb.beginText();
cb.setFontAndSize(bold, 80);
cb.showTextAligned(Element.ALIGN_CENTER, "CONFIDENTIAL", centreX, centreY, 54.7f);
cb.endText();
cb.restoreState();
}
stamper.close();
Files: service/WatermarkService.java (existing PDFs), print/PageDecorator.drawWatermark (new PDFs).