Tuesday, 19 February 2019 02:08

Add Navigation Buttons to PDF in Java

Written by  support iceblue
Rate this item
(0 votes)

Adding navigation buttons to a PDF document makes it easy for readers to jump to a certain page from another page. This article demonstrates how we can create a button that redirects to a special page (for example, home page, last page and next page) or a particular page (for example, page 9) in PDF using Spire.PDF for Java.

Entire Code:

import com.spire.pdf.actions.PdfActionDestination;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.actions.PdfNamedAction;
import com.spire.pdf.fields.PdfButtonField;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.PdfRGBColor;
import com.spire.pdf.graphics.PdfTrueTypeFont;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class AddNavigationButton {

    public static void main(String[] args) throws Exception {

        //create a PdfDocument object and load a sample PDF file
        PdfDocument doc = new PdfDocument();

        //get the last page
        PdfPageBase lastPage = doc.getPages().get(doc.getPages().getCount() - 1);

        //allow creating forms in PDF

        //define float variables to specify the location and size of the button
        float x = 80;
        float y = 300;
        float width = 150;
        float height = 22;

        //create a truetype font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial Unicode MS", Font.PLAIN, 13), true);

        //add a button that navigates to the first page
        PdfButtonField btn_1 = new PdfButtonField(lastPage, "btn_1");
        Rectangle2D.Float rect = new Rectangle2D.Float(x, y, width, height);
        btn_1.setText("Return to Page 1");
        btn_1.setBackColor(new PdfRGBColor(Color.ORANGE));
        btn_1.setForeColor(new PdfRGBColor(Color.blue));
        btn_1.setBorderColor(new PdfRGBColor(Color.blue));
        PdfNamedAction namedAction = new PdfNamedAction(PdfActionDestination.FirstPage);

        //add a button that navigates to a particular page
        PdfButtonField btn_2 = new PdfButtonField(lastPage, "btn_2");
        rect = new Rectangle2D.Float( x, y + height + 5, width, height);
        btn_2.setText("Jump to Page 9");
        btn_2.setBackColor(new PdfRGBColor(Color.ORANGE));
        btn_2.setForeColor(new PdfRGBColor(Color.blue));
        btn_2.setBorderColor(new PdfRGBColor(Color.blue));
        PdfGoToAction goToAction = new PdfGoToAction(new PdfDestination(doc.getPages().get(8)));

        //save to file
        doc.saveToFile("NavigationButton.pdf", FileFormat.PDF);


Add Navigation Buttons to PDF in Java

Additional Info

  • tutorial_title: