DEV Community

loading...

Converting Excel to PDF in Java Application

jazzzzz profile image Jane ・2 min read

PDF is a portable document format that cannot be easily edited or modified. So sometimes when we send Excel files to others and don’t want the important formulas to be viewed or modified, we will convert the Excel to PDF. This article will demonstrate two methods to convert Excel to PDF by using Free Spire.XLS for Java:
(1) Convert the whole Excel workbook to PDF.
(2) Convert a single Excel worksheet to PDF.

Installation
Method 1: You need to download the Free Spire.XLS for Java and unzip it. And then add the Spire.Xls.jar file to your project as dependency.

Method 2: If you use maven, you can easily add the jar dependency by adding the following configurations to the pom.xml.

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <name>e-iceblue</name>
<url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.xls.free</artifactId>
        <version>2.2.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

The Excel test document including two worksheets:

Example 1:
Spire.XLS for Java offers a method of workbook.saveToFile() to save the whole Excel workbook to PDF in Java.

import com.spire.xls.*;

public class ExcelToPDF {
    public static void main(String[] args) {
        //Load the input Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Input.xlsx");

        //Fit to page
        workbook.getConverterSetting().setSheetFitToPage(true);

        //Save as PDF document
        workbook.saveToFile("ExcelToPDF.pdf",FileFormat.PDF);
    }
}
Enter fullscreen mode Exit fullscreen mode

Example 2:
Spire.XLS for Java offers a method of worksheet.saveToPdf() to save a single Excel worksheet to PDF in Java.

import com.spire.xls.*;

public class ExcelToPDF {
    public static void main(String[] args) {
        //Load the input Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("Input.xlsx");

        //Get the second worksheet
        Worksheet worksheet = workbook.getWorksheets().get(1);

        //Save as PDF document
        worksheet.saveToPdf("ToPDF2.pdf");
    }
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide