Java: How to Add Actions to PDF Documents
Enhancing PDF documents with interactive elements has become increasingly important for improving user engagement and functionality. Adding actions to PDFs, such as linking to document pages, executing JavaScript, or triggering a file opening, can significantly elevate the utility of these documents in various professional and personal applications. By incorporating such dynamic features using the Spire.PDF for Java library, developers will be able to unlock new possibilities for their PDF documents, making them more versatile and user-friendly. This article will demonstrate how to add actions to PDF documents with Spire.PDF for Java.
- How to Add Actions to PDF using Spire.PDF for Java
- Create Navigation Actions in PDF with Java
- Create File-Open Actions in PDF with Java
- Create Sound Actions in PDF with Java
- Create JavaScript Actions in PDF with Java
Install Spire.PDF for Java
First of all, you need 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 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>11.11.11</version>
</dependency>
</dependencies>
How to Add Actions to PDF using Spire.PDF for Java
Spire.PDF for Java enables developers to add a variety of actions to PDF documents, such as navigation actions, file-open actions, sound actions, and JavaScript actions. Below is a table of classes and their descriptions for commonly used actions:
| Class | Description |
| PdfGoToAction | Represents an action that navigates to a destination within the current document. |
| PdfLaunchAction | Represents an action that launches and opens a file. |
| PdfJavaScriptAction | Represents an action that executes JavaScript code. |
| PdfSoundAction | Represents an action that plays a sound. |
For more action classes and their descriptions, refer to Spire.PDF for Java action API references.
Actions can be added to PDF documents in two primary ways:
1. Using Action Annotations
This method involves creating an action and linking it to an annotation on the page. The action is displayed and triggered when the annotation is clicked.
General Steps:
- Create a PdfDocument instance and load a PDF document using PdfDocument.LoadFromFile() method.
- Create an action instance and set its properties.
- Optionally, draw cue text or images to indicate the action.
- Create a PdfActionAnnotation instance using the action instance and specify its location on the page.
- Add the action annotation to the page using PdfPageBase.getAnnotations.add() method.
- Save the document using PdfDocument.SaveToFile() method.
2. Assigning Actions to Document Events
Actions can also be assigned to document-level events such as opening, closing, or printing the document. These actions are triggered automatically when the specified events occur.
General Steps:
- Create a PdfDocument instance and load a PDF document using PdfDocument.LoadFromFile() method.
- Create an action instance and set its properties.
- Assign the action to a document event using the following methods:
- PdfDocument.setAfterOpenAction()
- PdfDocument.setAfterPrintAction()
- PdfDocument.setAfterSaveAction()
- PdfDocument.setBeforeCloseAction()
- PdfDocument.setBeforePrintAction()
- PdfDocument.setBeforeSaveAction()
- Save the document using PdfDocument.SaveToFile() method.
Create Navigation Actions in PDF with Java
The PdfGoToAction class can be used to create navigation actions in PDF documents, allowing users to jump to a specific location within the document. Below is a Java code example demonstrating how to create a navigation button in a PDF document.
- Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.annotations.PdfActionAnnotation;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfStringFormat;
import com.spire.pdf.graphics.PdfTextAlignment;
import com.spire.pdf.graphics.PdfTrueTypeFont;
import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
public class AddNavigationActionPDF {
public static void main(String[] args) {
// Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.loadFromFile("Sample.pdf");
// Create a PdfDestination object
PdfDestination destination = new PdfDestination(2, new Point2D.Float(0, 0), 0.8f);
// Create a PdfGoToAction object using the PdfDestination object
PdfGoToAction goToAction = new PdfGoToAction(destination);
// Draw a rectangle and the cue text on the first page
Rectangle2D rect = new Rectangle2D.Float(20, 30, 120, 20);
pdf.getPages().get(0).getCanvas().drawRectangle(PdfBrushes.getLightGray(), rect);
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 12), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
pdf.getPages().get(0).getCanvas().drawString("Click to go to page 2", font, PdfBrushes.getBlack(), rect, format);
// Create a PdfActionAnnotation object using the PdfGoToAction object
PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, goToAction);
// Add the annotation to the first page
pdf.getPages().get(0).getAnnotations().add(actionAnnotation);
// Save the document
pdf.saveToFile("output/PDFNavigationAction.pdf");
pdf.close();
}
}

Create File-Open Actions in PDF with Java
Developers can use the PdfLaunchAction class to create a file-open action in a PDF document. Below is a Java code example showing how to add a file-open action to a PDF document.
- Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.actions.PdfFilePathType;
import com.spire.pdf.actions.PdfLaunchAction;
import com.spire.pdf.annotations.PdfActionAnnotation;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfStringFormat;
import com.spire.pdf.graphics.PdfTextAlignment;
import com.spire.pdf.graphics.PdfTrueTypeFont;
import java.awt.*;
import java.awt.geom.Rectangle2D;
public class AddFileOpenActionPDF {
public static void main(String[] args) {
// Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.loadFromFile("Sample.pdf");
// Create a PdfLaunchAction object and set the file path
PdfLaunchAction launchAction = new PdfLaunchAction("C:/Example.pdf", PdfFilePathType.Absolute);
// Draw a rectangle and the cue text on the first page
Rectangle2D rect = new Rectangle2D.Float(20, 30, 120, 20);
pdf.getPages().get(0).getCanvas().drawRectangle(PdfBrushes.getLightGray(), rect);
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.BOLD, 12), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Center);
pdf.getPages().get(0).getCanvas().drawString("Click to open the file", font, PdfBrushes.getBlack(), rect, format);
// Create a PdfActionAnnotation object using the PdfLaunchAction object
PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, launchAction);
// Add the annotation to the first page
pdf.getPages().get(0).getAnnotations().add(actionAnnotation);
// Save the document
pdf.saveToFile("output/PDFFileOpenAction.pdf");
pdf.close();
}
}

Create Sound Actions in PDF with Java
The PdfSoundAction class is used to handle sound playback in PDF documents, enabling features such as background music and voice reminders. The Java code example below demonstrates how to create sound actions in PDF documents.
- Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.actions.PdfSoundAction;
import com.spire.pdf.annotations.PdfActionAnnotation;
import com.spire.pdf.general.PdfSoundChannels;
import com.spire.pdf.general.PdfSoundEncoding;
import com.spire.pdf.graphics.PdfImage;
import java.awt.geom.Rectangle2D;
public class AddSoundActionPDF {
public static void main(String[] args) {
// Create an instance of PdfDocument
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.loadFromFile("Sample.pdf");
// Create a PdfSoundAction object and set the audio property
PdfSoundAction soundAction = new PdfSoundAction("Music.wav");
soundAction.setRepeat(false);
soundAction.getSound().setBits(16);
soundAction.getSound().setChannels(PdfSoundChannels.Stereo);
soundAction.getSound().setEncoding(PdfSoundEncoding.Signed);
soundAction.getSound().setRate(44100);
// Draw the sound logo on the first page
PdfImage image = PdfImage.fromFile("Sound.jpg");
pdf.getPages().get(0).getCanvas().drawImage(image, new Rectangle2D.Float(40, 40, image.getWidth(), image.getHeight()));
// Create a PdfActionAnnotation object using the PdfSoundAction object at the location of the logo
Rectangle2D rect = new Rectangle2D.Float(40, 40, image.getWidth(), image.getHeight());
PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, soundAction);
// Add the annotation to the first page
pdf.getPages().get(0).getAnnotations().add(actionAnnotation);
// Save the document
pdf.saveToFile("output/PDFSoundAction.pdf");
pdf.close();
}
}

Create JavaScript Actions in PDF with Java
The PdfJavaScript class allows developers to create JavaScript actions within PDF documents, enabling custom interactive features such as creating dynamic forms, validating user input, and automating tasks. The following Java code example demonstrates how to add JavaScript actions to a PDF document.
- Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.actions.PdfJavaScript;
import com.spire.pdf.actions.PdfJavaScriptAction;
public class AddJavaScriptActionPDF {
public static void main(String[] args) {
// Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
// Load a PDF file
pdf.loadFromFile("Sample.pdf");
// Define the JavaScript code and use it to create an instance of PdfJavaScriptAction
String jsCode = """
app.alert({
cMsg: 'Welcome to the article on The Timeless Delight of Bread!\\n\\nThis article explores the rich history, varieties, and cultural significance of bread. Enjoy your reading!',
nIcon: 3,
cTitle: 'Document Introduction'
});
""";
PdfJavaScriptAction javaScriptAction = new PdfJavaScriptAction(jsCode);
// Set the JavaScript action as the action to be executed after opening the PDF file
pdf.setAfterOpenAction(javaScriptAction);
// Save the document
pdf.saveToFile("output/PDFJavaScriptAction.pdf");
pdf.close();
}
}

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.
Set an Expiration Date for PDF Document in Java
This article demonstrates how to set an expiration date for a PDF document using Spire.PDF for Java.
import com.spire.pdf.actions.PdfJavaScriptAction;
public class ExpiryDate {
public static void main(String[] args) {
//Create a PdfDocument object
PdfDocument doc = new PdfDocument();
//Load a PDF file
doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
//Set expiration date and warning information,and close the document through JavaScript
String javaScript = "var rightNow = new Date();"
+ "var endDate = new Date('June 20, 2020 23:59:59');"
+ "if(rightNow.getTime() > endDate)"
+ "app.alert('This document is no longer valid, please contact us for a updated one.',1);"
+ "this.closeDoc();";
//Create a PdfJavaScriptAction object based on the javascript
PdfJavaScriptAction js = new PdfJavaScriptAction(javaScript);
//Set PdfJavaScriptAction as the AfterOpenAction
doc.setAfterOpenAction(js);
//Save to file
doc.saveToFile("ExpirationDate.pdf", FileFormat.PDF);
}
}

Java: Add Navigation Buttons to PDF
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>11.11.11</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);
}
}

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.