How to use PDFBox to create a link i can click to go to another page in the same document

AutoStudent :

I am trying to use PDFBox to create a link i can click to go to another page in the same document.

From this question (How to use PDFBox to create a link that goes to *previous view*?) I see that this should be easy to do, but when i try to do it I get this error: Exception in thread "main" java.lang.IllegalArgumentException: Destination of a GoTo action must be a page dictionary object

I am using this code:

//Loading an existing document consisting of 3 empty pages.
    File file = new File("C:\\Users\\Student\\Documents\\MyPDF\\Test_doc.pdf");
    PDDocument document = PDDocument.load(file);
    PDPage page = document.getPage(1);

    PDAnnotationLink link         = new PDAnnotationLink();
    PDPageDestination destination = new PDPageFitWidthDestination();
    PDActionGoTo action           = new PDActionGoTo();

    destination.setPageNumber(2);
    action.setDestination(destination);
    link.setAction(action);
    link.setPage(page);

I am using PDFBox 2.0.13, can anyone give me some guidance on what I'm doing wrong?

Appreciate all answers.

mkl :

First of all, for a local link ("a link i can click to go to another page in the same document"), destination.setPageNumber is the wrong method to use, cf. its JavaDocs:

/**
 * Set the page number for a remote destination. For an internal destination, call 
 * {@link #setPage(PDPage) setPage(PDPage page)}.
 *
 * @param pageNumber The page for a remote destination.
 */
public void setPageNumber( int pageNumber )

Thus, replace

destination.setPageNumber(2);

by

destination.setPage(document.getPage(2));

Furthermore, you forgot to set a rectangle area for the link and you forgot to add the link to the page annotations.

All together:

PDPage page = document.getPage(1);

PDAnnotationLink link         = new PDAnnotationLink();
PDPageDestination destination = new PDPageFitWidthDestination();
PDActionGoTo action           = new PDActionGoTo();

destination.setPage(document.getPage(2));
action.setDestination(destination);
link.setAction(action);
link.setPage(page);

link.setRectangle(page.getMediaBox());
page.getAnnotations().add(link);

(AddLink test testAddLinkToMwb_I_201711)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=159534&siteId=1