Add Watermarks to PDF in Java
Contents
[
Hide
]
Watermark artifacts let you place persistent visual markings on a page without mixing them into the main document content.
Add a watermark artifact
Use this example when the page should display a centered text watermark with custom rotation, opacity, and background placement.
- Open the source PDF Document.
- Create a WatermarkArtifact and configure its text state and placement settings.
- Add the watermark to the page and save the output file.
public static void addWatermarkArtifact(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
TextState textState = new TextState();
textState.setFontSize(72);
textState.setForegroundColor(Color.getBlueViolet());
textState.setFontStyle(FontStyles.Bold);
textState.setFont(FontRepository.findFont("Arial"));
WatermarkArtifact watermark = new WatermarkArtifact();
watermark.setTextAndState("WATERMARK", textState);
watermark.setArtifactHorizontalAlignment(HorizontalAlignment.Center);
watermark.setArtifactVerticalAlignment(VerticalAlignment.Center);
watermark.setRotation(60);
watermark.setOpacity(0.2);
watermark.setBackground(true);
document.getPages().get_Item(1).getArtifacts().add(watermark);
document.save(outputFile.toString());
}
}