Watermark Annotations using Java
Contents
[
Hide
]
Watermark annotations let you place reusable overlay content on a page while still managing it through the annotation collection.
Add a watermark annotation
Use this example when you need a text watermark annotation with custom font settings and opacity.
- Open the source PDF Document.
- Create a WatermarkAnnotation and add it to the page.
- Configure the TextState, watermark text, and opacity, then save the document.
public static void watermarkAdd(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
Page page = document.getPages().get_Item(1);
WatermarkAnnotation watermarkAnnotation = new WatermarkAnnotation(
page,
new Rectangle(100, 100, 400, 200, true));
page.getAnnotations().add(watermarkAnnotation);
TextState textState = new TextState();
textState.setForegroundColor(Color.getBlue());
textState.setFontSize(25);
textState.setFont(FontRepository.findFont("Arial"));
watermarkAnnotation.setOpacity(0.5);
watermarkAnnotation.setTextAndState(new String[]{"HELLO", "Line 1", "Line 2"}, textState);
document.save(outputFile.toString());
}
}
Get watermark annotations
This example scans the annotation collection and prints the rectangle of each watermark annotation.
- Open the source PDF Document.
- Iterate through the annotations on the target page.
- Filter annotations by AnnotationType.
Watermarkand print their rectangles.
public static void watermarkGet(Path inputFile) {
try (Document document = new Document(inputFile.toString())) {
for (Annotation a : document.getPages().get_Item(1).getAnnotations()) {
if (a.getAnnotationType() == AnnotationType.Watermark) {
System.out.println(a.getRect());
}
}
}
}
Delete watermark annotations
Use this approach when existing watermark annotations should be removed from the document.
- Open the source PDF Document.
- Collect annotations of type AnnotationType.
Watermark. - Delete the collected annotations and save the output file.
public static void watermarkDelete(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
List<Annotation> toDelete = new ArrayList<>();
for (Annotation a : document.getPages().get_Item(1).getAnnotations()) {
if (a.getAnnotationType() == AnnotationType.Watermark) {
toDelete.add(a);
}
}
for (Annotation a : toDelete) {
document.getPages().get_Item(1).getAnnotations().delete(a);
}
document.save(outputFile.toString());
}
}