Get Link Annotations in PDF using Java

Get Link annotation to PDF document programmaticaly using Aspose.PDF for Java Library

In order to annotate PDF file, 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

<repository>
    <id>AsposeJavaAPI</id>
    <name>Aspose Java AP</name>
    <url>https://releases.aspose.com/java/repo/</url>
</repository>

Dependency

<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>

Get Link Annotation via Java


You need Aspose.PDF for Java to try the code in your environment.

  • Load PDF in an instance of Document class
  • Create a new page or get a reference to an existing one
  • Create Link annotation
  • Call method Add for Link annotation from Page.Annotations collections
  • Save the file again

System Requirements


Aspose.PDF for Java is supported on all major operating systems. Just make sure that you have the following prerequisites.

  • Microsoft Windows or a compatible OS with Java Runtime Environment for JSP/JSF Application and Desktop Applications.
  • Development environment like Eclipse or IntelliJ IDEA
  • Aspose.PDF for Java library referenced in your project.

Get Link Annotations from PDF - Java

Example

    public static void GetLinkAnnotations() {

        // Load the PDF file
        Document document = new Document(_dataDir + "SimpleResume_mod.pdf");

        // Filter annotations using AnnotationSelector
        Page page = document.getPages().get_Item(1);
        AnnotationSelector annotationSelector = new AnnotationSelector(
                new LinkAnnotation(page, Rectangle.getTrivial()));
        page.accept(annotationSelector);
        List<Annotation> linkAnnotations = annotationSelector.getSelected();

        // print results
        for (Annotation la : linkAnnotations) {

            LinkAnnotation l = (LinkAnnotation) la;

            // Print the URL of each Link Annotation
            System.out.println("URI: " + ((GoToURIAction) l.getAction()).getURI());

            TextAbsorber absorber = new TextAbsorber();
            absorber.getTextSearchOptions().setLimitToPageBounds(true);
            absorber.getTextSearchOptions().setRectangle(l.getRect());
            page.accept(absorber);

            String extractedText = absorber.getText();

            // Print the text associated with hyperlink
            System.out.println(extractedText);
        }
    }