Watermark Annotations using Java

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.

  1. Open the source PDF Document.
  2. Create a WatermarkAnnotation and add it to the page.
  3. 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.

  1. Open the source PDF Document.
  2. Iterate through the annotations on the target page.
  3. Filter annotations by AnnotationType.Watermark and 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.

  1. Open the source PDF Document.
  2. Collect annotations of type AnnotationType.Watermark.
  3. 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());
    }
}