Извлечение PDF‑ссылок в Java

Вы можете проверять ссылки PDF, перебирая аннотации страниц и отфильтровывая AnnotationType.Link.

Извлечение аннотаций ссылок

Используйте этот пример, когда вам нужна информация о местоположении и странице для аннотаций ссылок на странице.

  1. Откройте исходный PDF в объекте Document.
  2. Переберите аннотации страницы и отфильтруйте аннотации ссылок.
  3. Прочитайте индекс страницы и прямоугольник для каждой подходящей ссылки.
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());
            }
        }
    }
}

Извлечение назначений гиперссылок

Используйте этот пример, когда нужно прочитать целевые URI из аннотаций веб-ссылок.

  1. Откройте исходный PDF в объекте Document.
  2. Найдите объекты LinkAnnotation, действие которых является GoToURIAction.
  3. Выведите индекс страницы и целевой URI для каждой гиперссылки.
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());
                }
            }
        }
    }
}