How to Work with Annotations in Java
Add a Widget Annotation
WidgetAnnotation represents a form control widget. Set the border color and caption
via AppearanceCharacteristics. After configuring the annotation, add it to the page’s
annotation collection and save the document:
try (Document doc = new Document()) {
Page page = doc.getPages().add();
WidgetAnnotation w = new WidgetAnnotation(page, new Rectangle(50, 50, 150, 80));
w.getCharacteristics().setBorder(Color.fromRgb(0, 0, 1));
w.getCharacteristics().setCaption("Submit");
page.getAnnotations().add(w);
doc.save("widget.pdf");
}Add a Free Text Annotation
A FreeTextAnnotation displays a text comment at a specific location on the page.
The default appearance defines the font and color of the annotation text:
try (Document doc = new Document()) {
Page page = doc.getPages().add();
DefaultAppearance da = new DefaultAppearance("Helv", 12, Color.BLACK);
FreeTextAnnotation fta = new FreeTextAnnotation(page,
new Rectangle(100, 300, 350, 350), da);
fta.setContents("Review this section carefully.");
page.getAnnotations().add(fta);
doc.save("freetext.pdf");
}Add a Highlight Annotation
HighlightAnnotation visually marks a text region on the page. Position it using
a Rectangle that covers the text to highlight:
try (Document doc = new Document("input.pdf")) {
Page page = doc.getPages().get(1);
HighlightAnnotation h = new HighlightAnnotation(page,
new Rectangle(100, 200, 400, 220));
page.getAnnotations().add(h);
doc.save("highlighted.pdf");
}Count Annotations on a Page
Access the page’s annotation collection directly to count or iterate annotations:
try (Document doc = new Document("input.pdf")) {
Page page = doc.getPages().get(1);
int count = page.getAnnotations().size();
System.out.println("Annotations on page 1: " + count);
}Remove Annotations
Use PdfAnnotationEditor to remove all annotations of a specific type from a document.
Call deleteAnnotations(type) with the annotation type name, then save:
try (PdfAnnotationEditor editor = new PdfAnnotationEditor()) {
editor.bindPdf("input.pdf");
editor.deleteAnnotations("Highlight");
editor.save("output.pdf");
}Flatten Annotations
Flattening annotations merges them permanently into the page content so they are no longer editable or removable as separate objects:
try (PdfAnnotationEditor editor = new PdfAnnotationEditor()) {
editor.bindPdf("annotated.pdf");
editor.flattenAnnotations();
editor.save("flat.pdf");
}