Extrair links de PDF em Java

Você pode inspecionar links de PDF iterando sobre as anotações da página e filtrando por AnnotationType.Link.

Use este exemplo quando precisar da localização e das informações de página para anotações de link em uma página.

  1. Abra o PDF de origem em um objeto Document.
  2. Itere através das anotações da página e filtre as anotações de link.
  3. Leia o índice da página e o retângulo para cada link correspondente.
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());
            }
        }
    }
}

Use este exemplo quando precisar ler os URIs de destino de anotações de link da web.

  1. Abra o PDF de origem em um objeto Document.
  2. Encontrar objetos LinkAnnotation cuja ação é um GoToURIAction.
  3. Imprima o índice da página e o destino URI para cada hyperlink.
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());
                }
            }
        }
    }
}