News Category

Annotation

Annotation (4)

Java: Get Annotations from PDF

2021-10-21 07:49:04 Written by support iceblue

PDF Annotations are additional objects added to a PDF document. Sometimes you may need to extract these additional data from the PDF file so as to learn about the annotation details without opening the document. In this article, we will describe how to get the annotations from PDF in Java using Spire.PDF for Java.

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>10.4.4</version>
    </dependency>
</dependencies>
    

Get Annotations from a PDF File

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 PdfDocument 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.
  • Java
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("Annotations.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’ author
                content.append("Annotation Author: " + annotations.get(i).getAuthor()+"\n");

                //Get the annotations’ text
                content.append("Annotation Text: " + annotations.get(i).getText()+"\n");

                //Get the annotations’ modified date
                String modifiedDate = annotations.get(i).getModifiedDate().toString();
                content.append("Annotation ModifiedDate: " + modifiedDate+"\n");

                //Get the annotations’ name
                content.append("Annotation Name: " + annotations.get(i).getName()+"\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();
        }
    }

Java: Get Annotations from PDF

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 for yourself.

PDF annotations are notes or markers added to documents, which are great for making comments, giving explanations, giving feedback, etc. Co-creators of documents often communicate with annotations. However, when the issues associated with the annotations have been dealt with or the document has been finalized, it is necessary to remove the annotations to make the document more concise and professional. This article shows how to delete PDF annotations programmatically using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required 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 in your application 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>10.4.4</version>
    </dependency>
</dependencies>
    

Remove the Specified Annotation

Annotations are page-level document elements. Therefore, deleting an annotation requires getting the page where the annotation is located first, and then you can use the PdfPageBase.getAnnotationsWidget().removeAt() method to delete the annotation. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first page using PdfDocument.getPages().get() method.
  • Remove the first annotation from this page using PdfPageBase.getAnnotationsWidget().removeAt() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

public class RemoveAnnotation {
    public static void main(String[] args) {

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("C:/Annotations.pdf");

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

        //Remove the first annotation
        page.getAnnotationsWidget().removeAt(0);

        //Save the document
        pdf.saveToFile("RemoveOneAnnotation.pdf");
    }
}

Java: Remove Annotations from PDF Documents

Remove All Annotations from a Page

Spire.PDF for Java also provides PdfPageBase.getAnnotationsWidget().clear() method to remove all annotations in the specified page. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first page using PdfDocument.getPages().get() method.
  • Remove all annotations from the page using PdfPageBase.getAnnotationsWidget().clear() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

public class RemoveAllAnnotationPage {
    public static void main(String[] args) {

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("C:/Annotations.pdf");

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

        //Remove all annotations in the page
        page.getAnnotationsWidget().clear();

        //Save the document
        pdf.saveToFile("RemoveAnnotationsPage.pdf");
    }
}

Java: Remove Annotations from PDF Documents

Remove All Annotations from a PDF Document

To remove all annotations from a PDF document, we need to loop through all pages in the document and delete all annotations from each page. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Loop through all pages to delete annotations.
  • Delete annotations in each page using PdfPageBase.getAnnotationsWidget().clear() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;

public class RemoveAllAnnotations {
    public static void main(String[] args) {

        //Create an object of PdfDocument
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("C:/Users/Sirion/Desktop/Annotations.pdf");

        //Loop through the pages in the document
        for (PdfPageBase page : (Iterable) pdf.getPages()) {
            //Remove annotations in each page
            page.getAnnotationsWidget().clear();
        }

        //Save the document
        pdf.saveToFile("RemoveAllAnnotations.pdf");
    }
}

Java: Remove Annotations from PDF Documents

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 for yourself.

PDF annotations help users make comments and mark up text. They are used in many situations where PDF files are involved, such as giving feedback on reports, making explanations for difficult words, and taking notes while reading articles. Users can add many types of annotations to PDF documents, such as pop-up, text box, link, and line annotations. This article will show how to add pop-up and text box annotations in PDF documents using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required 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 in your application 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>10.4.4</version>
    </dependency>
</dependencies>
    

Add a Pop-Up Annotation to a PDF Document

Pop-up annotations are displayed as buttons in PDF documents. They do not show annotation text on PDF pages, but only in the Comments widget of PDF viewers. The detailed steps for adding a pop-up annotation to a PDF document are as follows.

  • Create an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first page of the document using PdfDocument.getPages().get() method.
  • Find the text to annotate using PdfPageBase.findText().getFinds() method.
  • Create a PdfPopupAnnotation object and set the text and position of the annotation.
  • Set the style and color of the annotation using methods under PdfPopupAnnotation class.
  • Add the annotation to the page using PdfPageBase.getAnnotationsWidget().add() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
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 PDFPopUpAnnotation {
    public static void main(String[] args)  {

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

        //Load a PDF Document
        pdf.loadFromFile("Born That Way.pdf");

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

        //Find the text to add annotation
        PdfTextFind[] find = page.findText("developmental scientists").getFinds();

        //Create a PdfPopupAnnotation object and set the text and position of the annotation
        String text = "Developmental scientists are researchers who explores and summarizes the growth process of children.";
        float a = (float)(find[0].getPosition().getX() + find[0].getSize().getWidth() - 20);
        float b = (float)(find[0].getPosition().getY());
        Rectangle2D rectangle2D = new Rectangle.Float();
        rectangle2D.setFrame(new Point2D.Double(a,b),new Dimension());
        PdfPopupAnnotation annotation = new PdfPopupAnnotation(rectangle2D, text);

        //Set the text, position, and style of the annotation
        annotation.setIcon(PdfPopupIcon.Note);
        annotation.setColor(new PdfRGBColor(Color.red));

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

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

Java: Add Pop-Up and Text Box Annotations to PDF

Add a Text Box Annotation to a PDF Document

Pop-up annotations are displayed as buttons on PDF pages. The annotation text of pop-up annotations is not displayed directly on the page, but it will appear on the page when the mouse cursor is moved to the button. Readers can also directly open the "Comments" interface to view pop-up annotations directly. The detailed steps to add a text box annotation to a PDF document are as follows.

  • Create an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the first page using PdfDocument.getPages().get() method.
  • Find the text to annotate using PdfPageBase.findText.getFinds() method.
  • Create a PdfFreeTextAnnotation object and set the position of the annotation.
  • Set the text, font, text color, and text box format of the annotation using methods under PdfFreeTextAnnotation class.
  • Add the annotation to the page using PdfPageBase.getAnnotationsWidget().add() method.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
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("Born That Way.pdf");

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

        //Find the text to annotate
        PdfTextFind[] find = page.findText("developmental scientists").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, 150, 30);
        PdfFreeTextAnnotation textAnnotation = new PdfFreeTextAnnotation(rect);

        //Set the text, font, text color, and text box format of the annotation
        textAnnotation.setMarkupText("Scientists who research the growth process of children.");
        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();
    }
}

Java: Add Pop-Up and Text Box Annotations to PDF

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 for yourself.

When it comes to PDF documents, stamps offer an indispensable feature for adding contextual information and visual elements. These stamps can range from simple notes to complex graphics, enabling users to annotate, emphasize, or personalize their PDF content. With the ability to place stamps strategically, businesses can streamline workflows, indicate approvals, or provide concise feedback.

In this article, you will learn how to programmatically add dynamic stamps and image stamps to a PDF document using Spire.PDF for Java.

Install Spire.PDF for Java

To start, make sure to add the Spire.Pdf.jar file as a dependency in your Java program. You can download Spire.PDF for Java from our website and manually import the JAR file into your application. If you are using Maven, simply add the following code to your project's pom.xml file to include the JAR file effortlessly.

<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>10.4.4</version>
    </dependency>
</dependencies>
    

Prior Knowledge

In PDF, a stamp refers to an annotation or graphical element that can be added to a document to provide additional information. Spire.PDF for Java introduces the PdfRubberStampAnnotation class, which serves as a representation of a rubber stamp. To create the visual representation of a rubber stamp, the PdfTemplate class is employed. This class acts as a canvas allowing you to draw various types of information, including text, images, shapes, and date/time elements.

Add a Dynamic Stamp to PDF in Java

A dynamic stamp refers to a customizable annotation that can be added to a PDF document to indicate a specific status, approval, or other information. Unlike static stamps, dynamic stamps contain variables or fields that can be dynamically updated, such as the current date, time, username, or any other custom data.

The following are the steps to add a dynamic stamp to PDF using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.loadFromFile() method.
  • Create a PdfTemplate object with desired size.
  • Draw strings (including dynamic information such as date and time) on the template using PdfTemplate.getGraphics().drawString() method.
  • Create a PdfRubberStampAnnotation object, and set the template as its appearance.
  • Add the stamp to a specific PDF page using PdfPageBase.getAnnotationsWidget().add() method.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.annotations.PdfRubberStampAnnotation;
import com.spire.pdf.annotations.appearance.PdfAppearance;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.SimpleDateFormat;

public class AddDynamicStampToPdf {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument document = new PdfDocument();

        // Load a PDF file
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Get the last page
        PdfPageBase page = document.getPages().get(document.getPages().getCount() - 1);

        // Create a PdfTemplate object
        PdfTemplate template = new PdfTemplate(195, 50);

        // Create two fonts
        PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Elephant", Font.ITALIC, 15), true);
        PdfTrueTypeFont font2 = new PdfTrueTypeFont(new Font("Arial", Font.ITALIC, 10), true);

        // Create a solid brush and a gradient brush
        PdfSolidBrush solidBrush = new PdfSolidBrush(new PdfRGBColor(Color.black));
        Rectangle2D rect1 = new Rectangle2D.Float();
        rect1.setFrame(new Point2D.Float(0, 0), template.getSize());
        PdfLinearGradientBrush linearGradientBrush = new PdfLinearGradientBrush(rect1, new PdfRGBColor(Color.white), new PdfRGBColor(Color.orange), PdfLinearGradientMode.Horizontal);

        // Create rounded rectangle path
        int CornerRadius = 10;
        PdfPath path = new PdfPath();
        path.addArc(template.getBounds().getX(), template.getBounds().getY(), CornerRadius, CornerRadius, 180, 90);
        path.addArc(template.getBounds().getX() + template.getWidth() - CornerRadius, template.getBounds().getY(), CornerRadius, CornerRadius, 270, 90);
        path.addArc(template.getBounds().getX() + template.getWidth() - CornerRadius, template.getBounds().getY() + template.getHeight() - CornerRadius, CornerRadius, CornerRadius, 0, 90);
        path.addArc(template.getBounds().getX(), template.getBounds().getY() + template.getHeight() - CornerRadius, CornerRadius, CornerRadius, 90, 90);
        path.addLine(template.getBounds().getX(), template.getBounds().getY() + template.getHeight() - CornerRadius, template.getBounds().getX(), template.getBounds().getY() + CornerRadius / 2);

        // Draw path on the template
        template.getGraphics().drawPath(linearGradientBrush, path);
        template.getGraphics().drawPath(PdfPens.getRed(), path);

        // Draw dynamic text on the template
        String s1 = "APPROVED\n";
        String s2 = "By Manager at " + dateToString(new java.util.Date(), "yyyy-MM-dd HH:mm:ss");
        template.getGraphics().drawString(s1, font1, solidBrush, new Point2D.Float(5, 5));
        template.getGraphics().drawString(s2, font2, solidBrush, new Point2D.Float(2, 28));

        // Create a rubber stamp, specifying its size and location
        Rectangle2D rect2 = new Rectangle2D.Float();
        rect2.setFrame(new Point2D.Float(50, (float) (page.getActualSize().getHeight() - 300)), template.getSize());
        PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect2);

        // Create a PdfAppearance object and apply the template as its normal state
        PdfAppearance appearance = new PdfAppearance(stamp);
        appearance.setNormal(template);

        // Apply the appearance to stamp
        stamp.setAppearance(appearance);

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

        // Save the file
        document.saveToFile("output/DynamicStamp.pdf");
        document.close();
    }

    // Convert date to string
    public static String dateToString(java.util.Date date, String dateFormat) {
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        return format.format(date);
    }
}

Java: Add Stamps to a PDF Document

Add an Image Stamp to PDF in Java

An image stamp in PDF refers to a graphical element that is added to a document as an annotation or overlay. It involves placing an image onto a specific location within a PDF page.

The steps to add an image stamp to PDF using Spire.PDF for Java are as follows.

  • Create a PdfDocument object.
  • Load a PDF file using PdfDocument.loadFromFile() method.
  • Load an image that you want to stamp on PDF using PdfImage.fromFile() method.
  • Create a PdfTemplate object based on the size of the image.
  • Draw the image on the template using PdfTemplate.getGraphics().drawImage() method.
  • Create a PdfRubberStampAnnotation object, and set the template as its appearance.
  • Add the stamp to a specific PDF page using PdfPageBase.getAnnotationsWidget().add() method.
  • Save the document to a different PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.annotations.PdfRubberStampAnnotation;
import com.spire.pdf.annotations.appearance.PdfAppearance;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTemplate;

import java.awt.geom.Rectangle2D;

public class AddImageStampToPdf {

    public static void main(String[] args) {

        // Create a PdfDocument object
        PdfDocument document = new PdfDocument();

        // Load a PDF document
        document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.pdf");

        // Get the last page
        PdfPageBase page = document.getPages().get(document.getPages().getCount() - 1);

        // Load an image file
        PdfImage image = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\stamp-image.png");

        // Get the width and height of the image
        int width = image.getWidth();
        int height = image.getHeight();

        // Create a PdfTemplate object based on the size of the image
        PdfTemplate template = new PdfTemplate(width, height);

        // Draw image on the template
        template.getGraphics().drawImage(image, 0, 0, width, height);

        // Create a rubber stamp annotation, specifying its location and position
        Rectangle2D rect = new Rectangle2D.Float((float) (page.getActualSize().getWidth() - width - 50), (float) (page.getActualSize().getHeight() - 400), width, height);
        PdfRubberStampAnnotation stamp = new PdfRubberStampAnnotation(rect);

        // Create a PdfAppearance object
        PdfAppearance pdfAppearance = new PdfAppearance(stamp);

        // Set the template as the normal state of the appearance
        pdfAppearance.setNormal(template);

        // Apply the appearance to the stamp
        stamp.setAppearance(pdfAppearance);

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

        // Save the file
        document.saveToFile("output/ImageStamp.pdf");
        document.close();
    }
}

Java: Add Stamps to a PDF Document

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 for yourself.