Java: Add Navigation Buttons to PDF

2023-02-20 02:08:00 Written by Koohji

When reading a large PDF document, the reader may get frustrated by scrolling up and down to find information. Therefore, to enhance the reading experience, authors can embed navigation tools in PDF documents. The navigation button is one of those useful navigation tools, especially for navigating to related information. It is displayed on the page as a button with prompt text, which readers can click to jump to a specific location of the document easily. This article is going to demonstrate how to add navigation buttons to PDF documents in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>12.6.4</version>
    </dependency>
</dependencies>

Insert Navigation Buttons to a PDF Document

Spire.PDF for Java provides the PdfButtonField class to represent a button in a PDF document, and the methods under this class can be used to set the format and action of the button. We can create a custom method addNavigationButton(), and then pass the button, action, rectangle, and string as parameters to the method to add a navigation button to a PDF document. The detailed steps are as follows.

  • Create an object of PdfDocument class.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Get the last page using PdfDocument.getPages().get() method.
  • Allow creating forms using PdfDocument.setAllowCreateForm().
  • Create a PdfButtonField object.
  • Create a PdfNamedAction object and set the action as jumping to the first page.
  • Define the location and size of the button and the text to be displayed.
  • Use the custom method addNavigationButton() to add a navigation button navigating to the first page.
  • Create another PdfButtonField object.
  • Create a PdfGoToAction object and set the action as jumping to the third page.
  • Define the location and size of the button and the text to be displayed.
  • Use the custom method addNavigationButton() to add a navigation button navigating to the third page.
  • Save the document using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.actions.PdfAction;
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.fields.PdfForm;
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 an object of PdfDocument class
        PdfDocument pdf = new PdfDocument();

        //Load a PDF document
        pdf.loadFromFile("Balance Sheet.pdf");

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

        //Allow creating forms in PDF
        pdf.setAllowCreateForm(true);

        //Create a PdfButtonField object
        PdfButtonField btn_1 = new PdfButtonField(lastPage, "btn_1");
        //Create a PdfNamedAction object and set the action as jumping to the first page
        PdfNamedAction namedAction = new PdfNamedAction(PdfActionDestination.FirstPage);
        //Define the location and size of the button and the text to be displayed
        float x = 150;
        float y = 300;
        float width = 170;
        float height = 22;
        Rectangle2D.Float rect = new Rectangle2D.Float(x, y, width, height);
        String text = "Jump to the first page";
        //Use the custom method to add a navigation button navigating to the first page
        addNavigationButton(btn_1, rect, text, namedAction);

        //Create another PdfButtonField object
        PdfButtonField btn_2 = new PdfButtonField(lastPage, "btn_2");
        //Create a PdfGoToAction object and set the action as jumping to the third page
        PdfGoToAction goToAction = new PdfGoToAction(new PdfDestination(pdf.getPages().get(2)));
        //Define the location and size of the button and the text to be displayed
        rect = new Rectangle2D.Float( x, y + height + 5, width, height);
        String text1 = "Jump to the third page";
        //Use the custom method to add a navigation button navigating to the third page
        addNavigationButton(btn_2, rect, text1, goToAction);

        //Save the document
        pdf.saveToFile("NavigationButton.pdf", FileFormat.PDF);
        pdf.close();
    }
    static void addNavigationButton(PdfButtonField btn, Rectangle2D.Float rect, String text, PdfAction action) {
        //Create a PdfTrueTypeFont object
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 13), true);
        //Set the location and size of the button
        btn.setBounds(rect);
        //Set the text font of the button
        btn.setFont(font);
        //Set the text to be displayed in the button
        btn.setText(text);
        //Set the background color of the button
        btn.setBackColor(new PdfRGBColor(Color.ORANGE));
        //Set the color of the displayed text
        btn.setForeColor(new PdfRGBColor(Color.blue));
        //Set the border color of the button
        btn.setBorderColor(new PdfRGBColor(Color.green));
        //Set an action as the mouse click response of the button
        btn.getActions().setMouseDown(action);
        //Add the button to the document
        PdfForm form = new PdfForm();
        form.getFields().add(btn);
    }
}

Java: Add Navigation Buttons to PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

This article demonstrates how to create a chart without reference to the worksheet data range using Spire.XLS.

Detail steps:

Step 1: Create a workbook and get the first worksheet.

Workbook wb = new Workbook();            
Worksheet sheet = wb.Worksheets[0];

Step 2: Add a chart to the worksheet.

Chart chart = sheet.Charts.Add();

Step 3: Add a series to the chart.

var series = chart.Series.Add();

Step 4: Add data.

series.EnteredDirectlyValues = new object[] { 10, 20, 30 };

Step 5: Save the file.

wb.SaveToFile("result.xlsx", ExcelVersion.Version2013);

Output:

Create Chart without Using Worksheet Data Range in C#

Full code:

using Spire.Xls;

namespace Create_chart
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a workbook
            Workbook wb = new Workbook();
            
            //Get the first worksheet
            Worksheet sheet = wb.Worksheets[0];

            //Add a chart to the worksheet
            Chart chart = sheet.Charts.Add();

            //Add a series to the chart
            var series = chart.Series.Add();

            //Add data 
            series.EnteredDirectlyValues = new object[] { 10, 20, 30 };

            //Save the file
            wb.SaveToFile("result.xlsx", ExcelVersion.Version2013);
        }
    }
}

This article demonstrates how to insert an image to a table cell in PowerPoint using Spire.Presentataion for Java.

import com.spire.presentation.FileFormat;
import com.spire.presentation.ITable;
import com.spire.presentation.Presentation;
import com.spire.presentation.drawing.FillFormatType;
import com.spire.presentation.drawing.IImageData;
import com.spire.presentation.drawing.PictureFillType;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;

public class InsertImageToTableCell {

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

        //create a Presentation object and load an example PowerPoint file
        Presentation presentation = new Presentation();
        presentation.loadFromFile("C:/Users/Administrator/Desktop/example.pptx");

        //append a table to the first slide
        Double[] widths = new Double[]{100d,100d};
        Double[] heights = new Double[]{100d,100d};
        ITable table = presentation.getSlides().get(0).getShapes().appendTable(100,100, widths, heights);

        //insert an image to the cell(0,0)
        table.get(0,0).getFillFormat().setFillType(FillFormatType.PICTURE);
        table.get(0,0).getFillFormat().getPictureFill().setFillType(PictureFillType.STRETCH);
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream("C:/Users/Administrator/Desktop/logo.png"));
        IImageData imageData = presentation.getImages().append(bufferedImage);
        table.get(0,0).getFillFormat().getPictureFill().getPicture().setEmbedImage(imageData);

        //save to file
        presentation.saveToFile("InsertImageToCell.pptx", FileFormat.PPTX_2013);
    }
}

Insert an Image to a PowerPoint Table in Java

page 163