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.
Extract watermark artifacts from a PDF
Use this example when you need to inspect existing watermark artifacts and read their text or position.
- Open the source PDF Document.
- Iterate through the artifact collection of the target page.
- Filter watermark pagination artifacts and print their text and rectangles.
public static void extractWatermarkFromPdf(Path inputFile) {
try (Document document = new Document(inputFile.toString())) {
for (Artifact artifact : document.getPages().get_Item(1).getArtifacts()) {
if (artifact.getType() == Artifact.ArtifactType.Pagination
&& artifact.getSubtype() == Artifact.ArtifactSubtype.Watermark) {
System.out.println(artifact.getText() + " " + artifact.getRectangle());
}
}
}
}
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());
}
}
Delete watermark artifacts
Use this approach when existing watermark artifacts should be removed from the page.
- Open the source PDF Document.
- Iterate through the page artifact collection in reverse order.
- Delete pagination artifacts whose subtype is watermark, then save the document.
public static void deleteWatermarkArtifact(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
for (int i = document.getPages().get_Item(1).getArtifacts().size(); i >= 1; i--) {
Artifact artifact = document.getPages().get_Item(1).getArtifacts().get_Item(i);
if (artifact.getType() == Artifact.ArtifactType.Pagination
&& artifact.getSubtype() == Artifact.ArtifactSubtype.Watermark) {
document.getPages().get_Item(1).getArtifacts().delete(artifact);
}
}
document.save(outputFile.toString());
}
}