Add Text Box Annotations to an Existing PDF Document in Java

Andrew Wilson
2 min readFeb 10, 2023

The previous post have introduced how to add annotations to a PDF document while creating it using a free API. This article will share how to add an annotation to specified text in an existing PDF document using the same API.

Installation (2 methods)

Method 1: Download the free API and unzip it. Then add the Spire.Pdf.jar file to your project as dependency.

Method 2: Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.pdf.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>

Add a Text Box Annotation to a PDF Document

The annotation text of a text box annotation is displayed directly on the page. The following sample code shows how to find the specified text and then add an annotation to it.

import com.spire.pdf.*;
import com.spire.pdf.annotations.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;
import com.spire.pdf.general.find.PdfTextFind;
public class PDFTextBoxAnnotation {
public static void main(String[] args) {

//Create an instance of PdfDocument class
PdfDocument doc = new PdfDocument();

//Load a PDF document
doc.loadFromFile("Sample.pdf");

//Get the first page
PdfPageBase page = doc.getPages().get(0);

//Find the text to annotate
PdfTextFind[] find = page.findText("Section Title").getFinds();

//Create a PdfFreeTextAnnotation object and set the position of the annotation
float x = (float)(find[0].getPosition().getX() + find[0].getSize().getWidth());
float y = (float)(find[0].getPosition().getY() + find[0].getSize().getHeight());
Rectangle2D.Float rect = new Rectangle2D.Float(x, y, 180, 15);
PdfFreeTextAnnotation textAnnotation = new PdfFreeTextAnnotation(rect);

//Set the text, font, text color, and text box format of the annotation
textAnnotation.setMarkupText("Key information about the document");
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial",0, 11));
textAnnotation.setFont(font);
PdfAnnotationBorder border = new PdfAnnotationBorder(0.3f);
textAnnotation.setBorder(border);
textAnnotation.setBorderColor(new PdfRGBColor(Color.pink));
textAnnotation.setColor(new PdfRGBColor(Color.YELLOW));
textAnnotation.setOpacity(0.7f);
textAnnotation.setTextMarkupColor(new PdfRGBColor(Color.black));

//Add the annotation to the page
page.getAnnotationsWidget().add(textAnnotation);

//Save the document
doc.saveToFile("TextBoxAnnotation.pdf");
doc.close();
}
}

--

--

Andrew Wilson

Explore C#, Java and Python solutions for processing Word/Excel/PowerPoint/PDF files.