In order to add Text Annotation, we’ll use Aspose.PDF for Java API which is a feature-rich, powerful and easy to use conversion API for Java platform. You can download its latest version directly from Maven and install it within your Maven-based project by adding the following configurations to the pom.xml.
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java AP</name>
<url>https://releases.aspose.com/java/repo/</url>
</repository>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>
Create Annotations in PDF document via Java
You need Aspose.PDF for Java to try the code in your environment.
- Load PDF in an instance of Document class.
- Create an annotation that you want to add to the PDF.
- Add the annotation to the Page object’s Annotations collection.
- Save the PDF file.
PDF Text Annotation - Java
Document document = new Document(_dataDir + "sample.pdf");
Page page = document.getPages().get_Item(1);
Rectangle rect = new Rectangle(200, 750, 400, 790);
TextAnnotation textAnnotation = new TextAnnotation(page, rect);
textAnnotation.setTitle("Aspose User");
textAnnotation.setSubject("Sample Subject");
textAnnotation.setState (AnnotationState.Accepted);
textAnnotation.setContents("Sample contents for the annotation");
textAnnotation.setOpen(true);
textAnnotation.setIcon(TextIcon.Circle);
Border border = new Border(textAnnotation);
border.setWidth(5);
border.setDash(new Dash(1, 1));
textAnnotation.setBorder(border);
textAnnotation.setRect(rect);
page.getAnnotations().add(textAnnotation);
document.save(_dataDir + "sample_textannot.pdf");