DEV Community

CodeSharing
CodeSharing

Posted on

Converting Excel to PDF in Java Application

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

Top comments (3)

Collapse
 
amjay1604 profile image
JISHAN ALI

I have a negative number in excel as (1234.12) . But when i am converting , it appearing as -1234.12.

Please suggest me how to exactly convert the data of excel into pdf without loosing any format setting of excel workbook.

Collapse
 
amjay1604 profile image
JISHAN ALI

Hi Jane.
Can you help me in this?

Collapse
 
codesharing profile image
CodeSharing

Hello, for the issue, you can contact the support team via email (support@e-iceblue.com) or forum (e-iceblue.com/forum/spire-xls-f4.html)