Search code examples
javapdfpdfboxacrobat

How to use PDFBox to create a link that goes to *previous view*?


By using PDFBox, it is easy to create a link that goes a particular page or page view by using PDPageDestination. For example, the following code will make a link that goes to page 9:

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

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

Problem:
Instead of going to a particular page, I would like to go to the previous view.

For example, suppose in a PDF file, each of P.1 and P.2 has a link that goes to P. 9. Now I would like to put on P. 9 a link that goes back to where the user started.

If the user started out at P.1 and clicked the link to P.9, he arrives at P.9. When he clicks the link on P. 9, he will go back to P.1, where he came from. But If he started out at P.2, then the link at P.9 will go back to P.2 instead.

Question: How do I achieve this with PDFBox?

FYI, with Adobe Acrobat, this can be achieved by adding an "execute a menu item" action to a link, and then choosing "Previous View" as the menu item, as shown in this screenshot:

Link to Acrobat screenshot


Solution

  • With the guidance of Tilman, I managed to solve my own problem.

    I cannot find a PDAction subclass that gives me the capability to add a "named action", so I created my own subclass, "PDActionNamed":

    class PDActionNamed extends PDAction {
    
        public static final String SUB_TYPE = "Named";    
    
        public PDActionNamed() {
            super();
            setSubType( SUB_TYPE );
        }
    
        public void setN( String s ) {
            action.setName( "N", s );
        }
    }
    

    To use the subclass,

    PDAnnotationLink link   = new PDAnnotationLink(); 
    PDActionNamed action = new PDActionNamed ();
    action.setN("GoBack");    // this is one of Acrobat's default named action
    link.setAction(action);
    

    It seems to work even on non-Javascript-supported PDF readers (e.g. SumatraPDF).