DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

How to Add, Get and Delete Annotations from PDF in Java applications

PDF Annotations are additional objects on PDF documents. Sometimes you may need to add, extract and remove these objects from the PDF file in order to gain additional information. In this article, we will demonstrate how work with PDF annotations by using Spire.PDF for Java from the following three parts.

  • Add annotation to PDF
  • Get Annotations from PDF
  • Remove annotations from PDF

Install Spire.PDF for Java

First of all, you need to add the Spire.PDF.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file by adding the following code to your project's pom.xml file.

<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</artifactId>
        <version>4.10.2</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

Add annotation to PDF

Spire.PDF for Java offers PdfPageBase.getAnnotationsWidget().add() method to add the annotation to the specified page of the document.
The following are the steps to add an annotation to the first page of PDF file:

  • Create an object of Document class.
  • Load a sample PDF document using PdfDocument.loadFromFile() method.
  • Use PdfPageBase.get() method to get the first page of the PDF document.
  • Define a location where to add the annotation by searching a string using PdfPageBase.findText().getFinds() method and get its location.
  • Define a text annotation and sent the format for the annotation.
  • Add the text annotation using PdfAnnotation.add() method to the desired page of pdf.
  • Save the document to file using PdfDocument.savetoFile() method.
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 Test {
    public static void main(String[] args) throws Exception {
        //load the document from file
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

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

        //search a string and get its location where to add the annotation
        PdfTextFind[] find = page.findText("New Zealand").getFinds();
        float x = (float)(find[0].getPosition().getX() - doc.getPageSettings().getMargins().getLeft() + find[0].getSize().getWidth()+20);
        float y = (float)(find[0].getPosition().getY() - doc.getPageSettings().getMargins().getTop()+20);

        //define a text annotation
        Rectangle2D.Float rect = new Rectangle2D.Float(x, y, 150, 30);
        PdfFreeTextAnnotation textAnnotation = new PdfFreeTextAnnotation(rect);

        // set the annotation text, font and format
        textAnnotation.setMarkupText("Text annotation added by Spire.PDF");
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial",0, 12));;
        textAnnotation.setFont(font);
        PdfAnnotationBorder border = new PdfAnnotationBorder(0.5f);
        textAnnotation.setBorder(border);
        textAnnotation.setBorderColor(new PdfRGBColor(Color.pink));
        textAnnotation.setColor(new PdfRGBColor(Color.YELLOW));
        textAnnotation.setOpacity(0.75f);
        textAnnotation.setTextMarkupColor(new PdfRGBColor(Color.black));

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

        //Save the document to file
        doc.saveToFile("output/FreeTextAnnotation.pdf");
        doc.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Add annotation

Get Annotations from PDF

Spire.PDF for Java offers PdfPageBase.getAnnotationsWidget() method to get the annotation collection of the specified page of the document.
The following are the steps to get all the annotations from the first page of PDF file:

  • Create an object of Document class.
  • Load a sample PDF document using PdfDocument.loadFromFile() method.
  • Create a StringBuilder object.
  • Get the annotation collection of the first page of the document by using PdfPageBase.getAnnotationsWidget() method.
  • Loop through the pop-up annotations, after extract data from each annotation using PdfAnnotation.getText()method, then append the data to the StringBuilder instance using StringBuilder.append() method.
  • Write the extracted data to a txt document using Writer.write() method.
import com.spire.pdf.*;
import com.spire.pdf.annotations.*;

import java.io.FileWriter;

public class Test {
    public static void main(String[] args) throws Exception {

        //Create an object of PdfDocument class.
        PdfDocument pdf = new PdfDocument();
        //Load the sample PDF document
        pdf.loadFromFile("FreeTextAnnotation.pdf");

        //Get the annotation collection of the first page of the document.
        PdfAnnotationCollection annotations = pdf.getPages().get(0).getAnnotationsWidget();

        //Create a StringBuilder object
        StringBuilder content = new StringBuilder();

        //Traverse all the annotations
        for (int i = 0; i < annotations.getCount(); i++) {

            //If it is the pop-up annotations, continue
            if (annotations.get(i) instanceof PdfPopupAnnotationWidget)
                continue;
            //Get the annotations’ text
            content.append("Annotation Text: " + annotations.get(i).getText()+"\n");
            //Get the annotations’ location
            content.append ("Annotation Location: " + annotations.get(i).getLocation()+"\n");
        }

        //Write to a .txt file
        FileWriter fw = new FileWriter("GetAnnotations.txt");
        fw.write(content.toString());
        fw.flush();
        fw.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

Extract annotation

Remove annotations from PDF

Spire.PDF for Java offers PdfPageBase.getAnnotationsWidget().clear() method to remove all the annotation collection of the specified page of the document.

The following are the steps to remove all the annotations from the first page of PDF file:

  • Create an object of Document class.
  • Load a sample PDF document using PdfDocument.loadFromFile() method.
  • Remove all annotations of the first page of the document by using PdfPageBase.getAnnotationsWidget().Clear() method.
  • Save the document to file using PdfDocument.savetoFile() method.
import com.spire.pdf.*;

public class Test {
    public static void main(String[] args) throws Exception {

        //Create an object of PdfDocument class.
        PdfDocument pdf = new PdfDocument();
        //Load the sample PDF document
        pdf.loadFromFile("FreeTextAnnotation.pdf");

         ////remove the first annotation from the first page
        //document.getPages().get(0).getAnnotationsWidget().removeAt(0);

        //Remove all the annotations
        pdf.getPages().get(0).getAnnotationsWidget().clear();

        //Save the document to file
        pdf.saveToFile("output/DeleteAllAnnotations_out.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

Delete Annotation
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license

Discussion (0)