Last active
March 7, 2025 10:33
Extract Links from PDF in Java. For details: https://kb.aspose.com/pdf/java/extract-links-from-pdf-in-java/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.aspose.pdf.*; | |
import java.util.List; | |
public class Main { | |
public static void main(String[] args) throws Exception {//main() method for fetching URI | |
License license = new License();//Initialize the PDF license | |
license.setLicense("license.lic");//Apply the license | |
Document pdfDocument = new Document("PdfWithLinks.pdf");// Load hyperlinks PDF | |
// Iterate all the pages | |
for (int pageNumber = 1; pageNumber <= pdfDocument.getPages().size(); pageNumber++) { | |
System.out.println("Processing Page " + pageNumber);// Display the current page number | |
Page pdfPage = pdfDocument.getPages().get_Item(pageNumber);// Get the current page | |
// Create an annotation selector to find link annotations on the page | |
AnnotationSelector linkSelector = new AnnotationSelector(new LinkAnnotation(pdfPage, Rectangle.getTrivial())); | |
// Extract all annotations from the current page | |
pdfPage.accept(linkSelector); | |
// Retrieve the list of selected link annotations | |
List<Annotation> linkAnnotations = linkSelector.getSelected(); | |
// Iterate through each link annotation | |
for (Annotation annotation : linkAnnotations) { | |
// Check if the annotation is a LinkAnnotation and has actions | |
if (annotation instanceof LinkAnnotation) { | |
LinkAnnotation linkAnnotation = (LinkAnnotation) annotation; | |
// Check if the LinkAnnotation has any associated actions | |
if (linkAnnotation.getAction() instanceof GoToURIAction) { | |
// Cast the action to a GoToURIAction to access the URI | |
GoToURIAction uriAction = (GoToURIAction) linkAnnotation.getAction(); | |
// Display the extracted URI | |
System.out.println("Found URI: " + uriAction.getURI()); | |
} | |
} | |
} | |
} | |
// Indicate that the process is complete | |
System.out.println("URI extraction completed."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment