Java (482)
Setting up the page layout in Excel is an important step to make your worksheets look polished and professional. Whether you’re printing a report or sharing it digitally, customizing options like margins, orientation, paper size, and scaling helps ensure your data is presented clearly and effectively. In this article, you will learn how to programmatically set page setup options in Excel in Java using Spire.XLS for Java.
- Set Page Margins in Excel in Java
- Set Page Orientation in Excel in Java
- Set Paper Size in Excel in Java
- Set Print Area in Excel in Java
- Set Scaling Factor in Excel in Java
- Set FitToPages Options in Excel in Java
- Set Headers and Footers in Excel in Java
Install Spire.XLS for Java
First of all, you're required to add the Spire.Xls.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.xls</artifactId>
<version>16.3.2</version>
</dependency>
</dependencies>
Set Page Margins in Excel in Java
The PageSetup class in Spire.XLS for Java allows you to customize page setup options for Excel worksheets. It provides methods like setTopMargin(), setBottomMargin(), setLeftMargin(), setRightMargin(), setHeaderMarginInch(), and setFooterMarginInch(), enabling you to adjust the top, bottom, left, right, header, and footer margins of a worksheet. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using the Workbook.loadFromFile() method.
- Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
- Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
- Set the top, bottom, left, right, header, and footer margins using the PageSetup.setTopMargin(), PageSetup.setBottomMargin(), PageSetup.setLeftMargin(), PageSetup.setRightMargin(), PageSetup.setHeaderMarginInch(), and PageSetup.setFooterMarginInch() methods.
- Save the modified workbook to a new file using the Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.PageSetup;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class PageMargins {
public static void main(String[] args) {
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.loadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.getPageSetup();
// Set top, bottom, left, and right margins for the worksheet
// The measure of the unit is Inch (1 inch = 2.54 cm)
pageSetup.setTopMargin(1);
pageSetup.setBottomMargin(1);
pageSetup.setLeftMargin(1);
pageSetup.setRightMargin(1);
pageSetup.setHeaderMarginInch(1);
pageSetup.setFooterMarginInch(1);
// Save the modified workbook to a new file
workbook.saveToFile("SetPageMargins.xlsx", ExcelVersion.Version2016);
workbook.dispose();
}
}

Set Page Orientation in Excel in Java
The PageSetup.setOrientation() method allows you to specify the page orientation for printing. You can choose between two options: portrait mode or landscape mode. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using the Workbook.loadFromFile() method.
- Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
- Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
- Set the page orientation using the PageSetup.setOrientation() method.
- Save the modified workbook to a new file using the Workbook.saveToFile() method.
- Java
import com.spire.xls.*;
public class PageOrientation {
public static void main(String[] args) {
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.loadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.getPageSetup();
pageSetup.setOrientation(PageOrientationType.Landscape);
// Save the modified workbook to a new file
workbook.saveToFile("SetPageOrientation.xlsx", ExcelVersion.Version2016);
workbook.dispose();
}
}

Set Paper Size in Excel in Java
The PageSetup.setPaperSize() method enables you to select from a variety of paper sizes for printing your worksheet. These options include A3, A4, A5, B4, B5, letter, legal, tabloid, and more. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using the Workbook.loadFromFile() method.
- Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
- Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
- Set the paper size using the PageSetup.setPaperSize() method.
- Save the modified workbook to a new file using the Workbook.saveToFile() method.
- Java
import com.spire.xls.*;
public class PaperSize {
public static void main(String[] args) {
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.loadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.getPageSetup();
// Set the paper size to A4
pageSetup.setPaperSize(PaperSizeType.PaperA4);
// Save the modified workbook to a new file
workbook.saveToFile("SetPaperSize.xlsx", ExcelVersion.Version2016);
workbook.dispose();
}
}

Set Print Area in Excel in Java
You can define the specific area to be printed by using the PageSetup.setPrintArea() method. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using the Workbook.loadFromFile() method.
- Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
- Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
- Set the print area using the PageSetup.setPringArea() method.
- Save the modified workbook to a new file using the Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.PageSetup;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class PrintArea {
public static void main(String[] args) {
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.loadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.getPageSetup();
// Set the print area of the worksheet to "A1:E5"
pageSetup.setPrintArea("A1:E5");
// Save the modified workbook to a new file
workbook.saveToFile("SetPrintArea.xlsx", ExcelVersion.Version2016);
workbook.dispose();
}
}

Set Scaling Factor in Excel in Java
To scale the content of your worksheet to a specific percentage of its original size, you can use the PageSetup.setZoom() method. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using the Workbook.loadFromFile() method.
- Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
- Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
- Set the scaling factor using the PageSetup.setZoom() method.
- Save the modified workbook to a new file using the Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.PageSetup;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class ScalingFactor {
public static void main(String[] args) {
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.loadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.getPageSetup();
// Set the scaling factor of the worksheet to 90%
pageSetup.setZoom(90);
// Save the modified workbook to a new file
workbook.saveToFile("SetScalingFactor.xlsx", ExcelVersion.Version2016);
workbook.dispose();
}
}

Set FitToPages Options in Excel in Java
Spire.XLS also provides the ability to adjust your worksheet content to fit a specific number of pages by using the PageSetup.setFitToPagesTall() and PageSetup.setFitToPagesWide() methods. The detailed steps are as follows.
- Create an object of the Workbook class.
- Load an Excel file using the Workbook.loadFromFile() method.
- Get a specific worksheet using the Workbook.getWorksheets().get(index) method.
- Access the PageSetup object of the worksheet using the Worksheet.getPageSetup() method.
- Fit the content of the worksheet to one page using the PageSetup.setFitToPagesTall() and PageSetup.setFitToPagesWide() methods.
- Save the modified workbook to a new file using the Workbook.saveToFile() method.
- Java
import com.spire.xls.ExcelVersion;
import com.spire.xls.PageSetup;
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;
public class FitToPages {
public static void main(String[] args) {
// Create a Workbook object
Workbook workbook = new Workbook();
// Load an Excel file
workbook.loadFromFile("Sample.xlsx");
// Get the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the PageSetup object of the worksheet
PageSetup pageSetup = sheet.getPageSetup();
// Fit the content of the worksheet within one page vertically (i.e., all rows will fit on a single page)
pageSetup.setFitToPagesTall(1);
// Fit the content of the worksheet within one page horizontally (i.e., all columns will fit on a single page)
pageSetup.setFitToPagesWide(1);
// Save the modified workbook to a new file
workbook.saveToFile("FitToPages.xlsx", ExcelVersion.Version2016);
workbook.dispose();
}
}

Set Headers and Footers in Excel in Java
For instructions on setting headers and footers in Excel, please refer to this article: Java: Add Headers and Footers to Excel.
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.
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>12.3.9</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.4.0</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.