Extraire des liens PDF en Java
Contents
[
Hide
]
Vous pouvez inspecter les liens PDF en parcourant les annotations de page et en filtrant AnnotationType.Link.
Extraire les annotations du lien
Utilisez cet exemple lorsque vous avez besoin des informations d’emplacement et de page pour les annotations de lien sur une page.
- Ouvrez le PDF source Document.
- Parcourez les annotations de page et filtrez les annotations de lien.
- Lisez l’index de la page et le rectangle pour chaque lien correspondant.
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());
}
}
}
}
Extraire les destinations des hyperliens
Utilisez cet exemple lorsque vous devez lire les URI cibles à partir des annotations de liens Web.
- Ouvrez le PDF source Document.
- Recherchez les objets LinkAnnotation dont l’action est une GoToURIAction.
- Imprimez l’index de la page et la cible URI pour chaque lien hypertexte.
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());
}
}
}
}
}