Tuesday, 25 August 2020

[Java] How to convert Excel to PDF using Java

Do you always need to share your Excel workbook with people who don’t have MS Office installed on their system? Do you always need your Excel spreadsheets to keep their format and look exactly the same when opened on different systems? If yes, Converting Excel to PDF will be a perfect way to deal with these problems.

In this tutorial, I’ll show you how to convert Excel to PDF using Java code and Spire.XLS for Java API from the following aspects.

l  Converting the whole Excel workbook to PDF

l  Converting each worksheet in Excel file to different PDF

l  Converting selected range in worksheet to PDF

l  Converting CSV file to PDF

Spire.XLS for Java is a professional Java Excel API that enables developers to create, manage, manipulate, convert and print Excel worksheets without using Microsoft Office or Microsoft Excel. At the same time, it also supports all three operation systems – Windows, Mac OS and Linux.

Add Spire.Xls.jar as dependency

Method 1: Download Free Spire.XLS for Java pack, unzip it and import Spire.Xls.jar located in the “lib” folder in your project as a dependency. You can find the steps from the following screenshot.



Method 2: If you are creating a Maven project, please specify e-iceblue Maven Repository configuration and define Free Spire.XLS for Java API dependency in your pom.xml as follows.

<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>

Finally, for IDEA, you need to click “Import Changes” to import the Spire.PDF jars, and for Eclipse, you just need to click the “Save” button.

Converting the whole Excel workbook to PDF

You first need to create a workbook and load an Excel example file, and then use the setSheetFitToPage method to adjust the width of worksheet. Finally, save the whole file to PDF using the workbook. saveToFile method.

import com.spire.xls.*;

public class WholeToPDF {
   
public static void main(String[] args) {
       
//Create a Workbook and load an Excel file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.xlsx");

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

       
//Save to PDF file
       
workbook.saveToFile("output/WholeToPDF.pdf",FileFormat.PDF);
        }
    }

Output

Convert each worksheet to different PDF

Spire.XLS for Java offers a method of worksheet. SaveToPdf to convert each worksheet to PDF.

import com.spire.xls.*;
public class EachWorksheetToPDF {
   
public static void main(String[] args) {
       
//Create a workbook and load an Excel file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.xlsx");
       
//Loop through all worksheets and save to different PDF files
       
for(int i = 0; i < workbook.getWorksheets().getCount(); i ++)
        {
            Worksheet worksheet = workbook.getWorksheets().get(i);
            String result =
"output/sheet-" + i + "-result.pdf";
            worksheet.saveToPdf(result);
        }
       }
 } 

Output


Converting selected Range in worksheet to PDF

The following are the steps to convert selected range in worksheet to PDF.

·      Create a workbook and load an Excel example file

·      Add a new sheet and copy the cells you want to convert to the new sheet.

·      Using the method autoFitColumns() to automatically fit the width.

·      Get the new sheet and save it to PDF file.

import com.spire.xls.*;
public class SelectedRangeToPDF {
   
public static void main(String[] args) {
       
//Create a workbook and load an Excel file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile(
"C:\\Users\\Test1\\Desktop\\Sample.xlsx");
       
//Add a new sheet to workbook
       
workbook.getWorksheets().add("NewSheet");
       
//Copy your area to new sheet
   
workbook.getWorksheets().get(0).getCellRange("A1:C7").copy(workbook.getWorksheets().get(1).getCellRange("A11:C17"), true );
       
//Auto fit column width
       
workbook.getWorksheets().get(1).getCellRange("A1:F17").autoFitColumns();
       
//Save the document
       
String output = "SelectedRangeToPDF.pdf";
        Worksheet worksheet = workbook.getWorksheets().get(
1);
        String result =
"output/selectedRangeToPDF.pdf";
        worksheet.saveToPdf(result);
    }
}

Output


Converting CSV to PDF

A Comma Separated Values (CSV) file is a plain text file that contains a list of data, and we

can open it in spreadsheet programs (such as Microsoft Excel), which make them easier to read.

import com.spire.xls.*;
public class CsvToPDF {
   
public static void main(String[] args) {
        String inputFile =
"C:\\Users\\Test1\\Desktop\\Sample.csv";
       
//Create a workbook and load a csv file
       
Workbook workbook = new Workbook();
        workbook.loadFromFile( inputFile,
",", 1, 1);
       
//Set the setSheetFitToPage property as true
       
workbook.getConverterSetting().setSheetFitToPage(true);
       
//Get the first worksheet
       
Worksheet sheet = workbook.getWorksheets().get(0);
       
//AutoFit a column if the characters in the column exceed column width
       
for (int i = 1; i < sheet.getColumns().length; i++)
        {
            sheet.autoFitColumn(i);
        }        
//Save to PDF document
       
String output = "output/CSVToPDF.pdf";
        workbook.saveToFile(output,  FileFormat.
PDF);     }
}

Output


Conclusion

In this article, we can learn how to easily convert Excel to PDF using Spire.XLS for Java. If there are still some problems about Java code, you can leave a note on our Forum.






No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...