Извлечение PDF‑ссылок в Java
Contents
[
Hide
]
Вы можете проверять ссылки PDF, перебирая аннотации страниц и отфильтровывая AnnotationType.Link.
Извлечение аннотаций ссылок
Используйте этот пример, когда вам нужна информация о местоположении и странице для аннотаций ссылок на странице.
- Откройте исходный PDF в объекте Document.
- Переберите аннотации страницы и отфильтруйте аннотации ссылок.
- Прочитайте индекс страницы и прямоугольник для каждой подходящей ссылки.
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 из аннотаций веб-ссылок.
- Откройте исходный PDF в объекте Document.
- Найдите объекты LinkAnnotation, действие которых является GoToURIAction.
- Выведите индекс страницы и целевой 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());
}
}
}
}
}