Reputation: 39
I am using the following code (Kotlin) to find hyperlinks in a PDF
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.interactive.action.PDActionURI
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink
import ... destination.PDPageXYZDestination
import java.io.File
fun findAnnotationsTest() {
val pdfPath = "LinkedPDF.pdf"
val doc = PDDocument.load(File(pdfPath))
var pageNo = 0
for (page in doc.pages) {
pageNo++
for (annotation in page.annotations) {
val subtype = annotation.subtype
println("Found Annotation ($subtype) on page $pageNo")
if (annotation is PDAnnotationLink) {
val aname = annotation.annotationName
println("\t\tfound Link named $aname on page $pageNo")
val link = annotation
println("\t\tas string: " + link.toString());
println("\t\tdestination: " + link.getDestination());
val dest = link.destination
val destClass = dest::class
println("\t\tdest class is $destClass")
if(dest is PDPageXYZDestination){
val pageNumber = dest.pageNumber
println("\t\tdest page number is $pageNumber")
}
val action = link.action
if (action == null) {
println("\t\tbut action is null")
continue
}
if (action is PDActionURI)
println("\t\tURI action is ${action.uri}")
else
println("\t\tother action is ${action::class}")
}
else{
println("\tNOT a link")
}
}
}
}
The input file has hundreds of (working) internal links.
This code finds the annotations and recognizes them as links, but with null PDActions and PDPageXYZDestination's with page number = -1. The output for each link looks like:
Found Annotation (Link) on page 216
found Link (Link) named null on page 216
as string: org.apache.pdfbox....annotation.PDAnnotationLink@3234e239
destination: org.apache.pdfbox.....destination.PDPageXYZDestination@3d921e20
dest class is class org.apache.pdfbox...destination.PDPageXYZDestination
dest page number is -1
but action is null
BTW, the PDF was created by saving an MS Word document (which had internal links to Word bookmarks) as a PDF.
Any ideas on what I'm doing wrong?
Here's the PDF (a sample): NBSample.pdf
Upvotes: 0
Views: 664
Reputation: 18851
The destination of PDPageDestination is not a number (this is only with external page links), it is a page dictionary, so additional efforts are needed to get the number (the method javadoc mentions this). Here a slightly modified excerpt of the PrintBookmarks.java example:
if (dest instanceof PDPageDestination)
{
PDPageDestination pd = (PDPageDestination) dest;
System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
}
Upvotes: 1