Extraer enlaces PDF en Java

Puede inspeccionar los enlaces PDF iterando sobre las anotaciones de la página y filtrando por AnnotationType.Link.

Extraer anotaciones de enlace

Utilice este ejemplo cuando necesite la ubicación e información de página para las anotaciones de enlace en una página.

  1. Abra el PDF de origen Document.
  2. Itere a través de las anotaciones de la página y filtre las anotaciones de enlace.
  3. Lea el índice de página y el rectángulo para cada enlace coincidente.
public static void extractLinkAnnotation(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        for (Annotation annotation : document.getPages().get_Item(1).getAnnotations()) {
            if (annotation.getAnnotationType() == AnnotationType.Link && annotation instanceof LinkAnnotation) {
                LinkAnnotation linkAnnotation = (LinkAnnotation) annotation;
                System.out.println("Page: " + linkAnnotation.getPageIndex()
                        + ", location: " + linkAnnotation.getRect());
            }
        }
    }
}

Extraer destinos de hipervínculos

Utilice este ejemplo cuando necesite leer los URI de destino de las anotaciones de enlaces web.

  1. Abra el PDF de origen Document.
  2. Busque LinkAnnotation objetos cuya acción es un GoToURIAction.
  3. Imprima el índice de página y el objetivo URI de cada hipervínculo.
public static void extractHyperlinks(Path inputFile) {
    try (Document document = new Document(inputFile.toString())) {
        for (Annotation annotation : document.getPages().get_Item(1).getAnnotations()) {
            if (annotation.getAnnotationType() == AnnotationType.Link && annotation instanceof LinkAnnotation) {
                LinkAnnotation linkAnnotation = (LinkAnnotation) annotation;
                if (linkAnnotation.getAction() instanceof GoToURIAction) {
                    GoToURIAction action = (GoToURIAction) linkAnnotation.getAction();
                    System.out.println("Page " + linkAnnotation.getPageIndex() + ", URI:" + action.getURI());
                }
            }
        }
    }
}