Java (481)
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.12.16</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.
Converting RTF to HTML helps improve accessibility as HTML documents can be easily displayed in web browsers, making them accessible to a global audience. While converting RTF to images can help preserve document layout as images can accurately represent the original document, including fonts, colors, and graphics. In this article, you will learn how to convert RTF to HTML or images in Java using Spire.Doc for Java.
Install Spire.Doc for Java
First of all, you're required to add the Spire.Doc.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.doc</artifactId>
<version>14.1.3</version>
</dependency>
</dependencies>
Convert RTF to HTML in Java
Converting RTF to HTML ensures that the document can be easily viewed and edited in any modern web browser without requiring any additional software.
With Spire.Doc for Java, you can achieve RTF to HTML conversion through the Document.saveToFile(String fileName, FileFormat.Html) method. The following are the detailed steps.
- Create a Document instance.
- Load an RTF document using Document.loadFromFile() method.
- Save the RTF document in HTML format using Document.saveToFile(String fileName, FileFormat.Html) method.
- Java
import com.spire.doc.*;
public class RTFToHTML {
public static void main(String[] args) {
// Create a Document instance
Document document = new Document();
// Load an RTF document
document.loadFromFile("input.rtf", FileFormat.Rtf);
// Save as HTML format
document.saveToFile("RtfToHtml.html", FileFormat.Html);
document.dispose();
}
}

Convert RTF to Image in Java
To convert RTF to images, you can use the Document.saveToImages() method to convert an RTF file into individual Bitmap or Metafile images. Then, the Bitmap or Metafile images can be saved as a BMP, EMF, JPEG, PNG, GIF, or WMF format files. The following are the detailed steps.
- Create a Document object.
- Load an RTF document using Document.loadFromFile() method.
- Convert the document to images using Document.saveToImages() method.
- Iterate through the converted image, and then save each as a PNG file.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
public class RTFtoImage {
public static void main(String[] args) throws Exception{
// Create a Document instance
Document document = new Document();
// Load an RTF document
document.loadFromFile("input.rtf", FileFormat.Rtf);
// Convert the RTF document to images
BufferedImage[] images = document.saveToImages(ImageType.Bitmap);
// Iterate through the image collection
for (int i = 0; i < images.length; i++) {
// Get the specific image
BufferedImage image = images[i];
// Save the image as png format
File file = new File("Images\\" + String.format(("Image-%d.png"), i));
ImageIO.write(image, "PNG", file);
}
}
}

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.
Text boxes in Microsoft Word are flexible elements that improve the layout and design of documents. They enable users to place text separately from the main text flow, facilitating the creation of visually attractive documents. At times, you might need to extract text from these text boxes for reuse, or update the content within them to maintain clarity and relevance. This article demonstrates how to extract or update textboxes in a Word document using Java with Spire.Doc for Java.
Install Spire.Doc for Java
First of all, you're required to add the Spire.Doc.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.doc</artifactId>
<version>14.1.3</version>
</dependency>
</dependencies>
Extract Text from a Textbox in Word in Java
With Spire.Doc for Java, you can access a specific text box in a document using the Document.getTextBoxes().get() method. You can then iterate through the child objects of the text box to check if each one is a paragraph or a table. For paragraphs, retrieve the text using the Paragraph.getText() method. For tables, loop through the cells to extract text from each cell.
Here are the steps to extract text from a text box in a Word document:
- Create a Document object.
- Load a Word file using Document.loadFromFile() method.
- Access a specific text box using Document.getTextBoxes().get() method.
- Iterate through the child objects of the text box.
- Check if a child object is a paragraph. If so, use Paragraph.getText() method to get the text.
- Check if a child object is a table. If so, use extractTextFromTable() method to retrieve the text from the table.
- Java
import com.spire.doc.*;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextBox;
import java.io.FileWriter;
import java.io.IOException;
public class ExtractTextFromTextbox {
public static void main(String[] args) throws IOException {
// Create a Document object
Document document = new Document();
// Load a Word file
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");
// Get a specific textbox
TextBox textBox = document.getTextBoxes().get(0);
// Create a FileWriter to write extracted text to a txt file
FileWriter fileWriter = new FileWriter("Extracted.txt");
// Iterate though child objects of the textbox
for (Object object: textBox.getChildObjects()) {
// Determine if the child object is a paragraph
if (((DocumentObject) object).getDocumentObjectType() == DocumentObjectType.Paragraph) {
// Write paragraph text to the txt file
fileWriter.write(((Paragraph)object).getText() + "\n");
}
// Determine if the child object is a table
if (((DocumentObject) object).getDocumentObjectType() == DocumentObjectType.Table) {
// Extract text from table to the txt file
extractTextFromTable((Table)object, fileWriter);
}
}
// Close the stream
fileWriter.close();
}
// Extract text from a table
static void extractTextFromTable(Table table, FileWriter fileWriter) throws IOException {
for (int i = 0; i < table.getRows().getCount(); i++) {
TableRow row = table.getRows().get(i);
for (int j = 0; j < row.getCells().getCount(); j++) {
TableCell cell = row.getCells().get(j);
for (Object paragraph: cell.getParagraphs()) {
fileWriter.write(((Paragraph) paragraph).getText() + "\n");
}
}
}
}
}

Update a Textbox in Word in Java
To modify a text box, first remove its existing content using TextBox.getChildObjects.clear() method. Then, create a new paragraph and assign the desired text to it.
Here are the steps to update a text box in a Word document:
- Create a Document object.
- Load a Word file using Document.loadFromFile() method.
- Get a specific textbox using Document.getTextBoxes().get() method.
- Remove existing content of the textbox using TextBox.getChildObjects().clear() method.
- Add a paragraph to the textbox using TextBox.getBody().addParagraph() method.
- Add text to the paragraph using Paragraph.appendText() method.
- Save the document to a different Word file.
- Java
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.Paragraph;
import com.spire.doc.fields.TextBox;
import com.spire.doc.fields.TextRange;
public class UpdateTextbox {
public static void main(String[] args) {
// Create a Document object
Document document = new Document();
// Load a Word file
document.loadFromFile("C:\\Users\\Administrator\\Desktop\\Input.docx");
// Get a specific textbox
TextBox textBox = document.getTextBoxes().get(0);
// Remove child objects of the textbox
textBox.getChildObjects().clear();
// Add a new paragraph to the textbox
Paragraph paragraph = textBox.getBody().addParagraph();
// Set line spacing
paragraph.getFormat().setLineSpacing(15f);
// Add text to the paragraph
TextRange textRange = paragraph.appendText("The text in this textbox has been updated.");
// Set font size
textRange.getCharacterFormat().setFontSize(15f);
// Save the document to a different Word file
document.saveToFile("UpdateTextbox.docx", FileFormat.Docx_2019);
// Dispose resources
document.dispose();
}
}

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.