Add annotation and save PDF programmatically

Adding annotations can be done programmatically using the AnnotationWriter.writeAnnotations(File, File, WritableAnnotation[]).

This static method accepts two File objects, the first is the input file and the second is the output. The final variable is an array of WritableAnnotation which represent the annotations you wish to add to the document.

WritableAnnotation is an abstract class that is extended by the classes in such as CircleAnnotation, SquareAnnotation and the other classes ending in Annotation.

Each of these classes has two constructors depending on your needs.

The first constructor allows you to pass in some basic details for the annotation and covers the basics for the annotation.

The second constructor also accepts a FormObject as an input, the FormObject can contain much more detailed information about the annotation but requires much more in-depth knowledge of the values used by annotations in the pdf spec.

For instance, the following would add two annotations, a square to page one at coordinates 10, 10, 100, 100 and a circle to page two at coordinates 10, 10, 100, 100.

WritableAnnotation[] annotations = new WritableAnnotation[2];
annotations[0] = new SquareAnnotation(1, 10, 10, 100, 100);
annotations[1] = new CircleAnnotation(2, 10, 10, 100, 100);
AnnotationWriter.writeAnnotations(inputFile, outputFile, annotation);

The JavaDoc for AnnotationWriter can also be found here with an example that creates one of each of the support annotation types.

Still need help? Send us your questions.