Summary of two methods of converting Excel to PDF in Java

Time:2022-5-3

Hello, Hello, I’m grey ape, a program ape who can write bugs!

There are many ways to use tools to convert Excel to PDF. Here I will introduce two common methods to deal with two different use scenarios. Next, I will give you a demonstration in the springboot environment!

1、 Convert PDF using spire

Firstly, a relatively simple method is introduced. This method can convert a sheet page or the whole excel file in our excel file into PDF format with just a few lines of code,

However, one disadvantage of this method is that the jar package is charged and can only export three sheet pages, which is not suitable for the conversion of Excel files with multiple sheet pages.

When using, first import the required dependencies of the workbook in the POM file:

         <dependency>
             <groupId>e-iceblue</groupId>
             <artifactId>spire.xls.free</artifactId>
             <version>2.2.0</version>
         </dependency>

1. Convert the entire excel file to PDF using spire

Using workbook to export the code of the whole excel file only needs two steps. We can directly look at the code example:

/**
      *Use spire to simply convert the whole Excel to PDF
      *
      *@ param inputfilepath excel file path
      *@ param outputfilepath PDF file path exported
      */
     public static void totalExcelToPDF(String inputFilePath, String outputFilePath) {
         Workbook wb = new Workbook();
 //Import excel file
         wb.loadFromFile(inputFilePath);
 //Export PDF file
         wb.saveToFile(outputFilePath, FileFormat.PDF);
     }

2. Specifies that a single sheet page is converted to PDF

Using spire, you can convert the specified single sheet page to PDF format output. Here, you need to enter the subscript of the specified sheet page. Code examples are as follows:

/**
      *Convert a single sheet to PDF using spire
      *
      *@ param inputfilepath excel file path
      *@ param outputfilepath PDF file path exported
      *@ param sheetnum exported sheet page subscript
      */
     public static void partExcelToPDF(String inputFilePath, String outputFilePath, int sheetNum) {
         //Load excel document
         Workbook wb = new Workbook();
         wb.loadFromFile(inputFilePath);
         //Which sheet page to get
         Worksheet sheet = wb.getWorksheets().get(sheetNum);
         //The calling method is saved in PDF format
         sheet.saveToPdf(outputFilePath);
     }

Although the above method of using spire to convert Excel to PDF is simple, it is not suitable for the conversion of large Excel files. It is only suitable for files with less than 3 sheet pages.

Therefore, in enterprise project development, if you want to convert a large number of Excel files or Excel files with more sheet pages into PDF format as a whole, the following method is recommended, which is stable and free!

2、 Use Jacob to convert Excel to PDF (recommended)

1. Environmental preparation

Before using Jacob, you need to make some preparations. First, you need to download Jacob’s compressed package Jacob Zip, download address:https://sourceforge.net/projects/jacob-project/

After decompression, the following contents are obtained:

Summary of two methods of converting Excel to PDF in Java

If you are a 64 bit system, use x64 DLL and 32-bit system use x86 DLL. After that, we need to put the DLL file into the bin directory of your JDK, as shown in the following figure:

Summary of two methods of converting Excel to PDF in Java

In this way, the preparatory work will be done,

Next, introduce the dependencies required by Jacob in Maven:

<!-- Jacob dependency -- >
         <dependency>
             <groupId>com.jacob</groupId>
             <artifactId>jacob</artifactId>
             <version>1.19</version>
             <scope>system</scope>
             <!-- Local Jacob Jar path -- >
             <systemPath>D:\DevInstall\jacob18,19\jacob-1.19\jacob.jar</systemPath>
         </dependency>

Note: the value of the tag in the above dependency is your Jacob The specific path of jar. Just change it to the corresponding path you just downloaded.

2. Perform export pdf

The method of exporting PDF from excel is as follows: the more important parts are annotated, and the method can be used directly!

​
     /**
      *Converting Excel to PDF using Jacob
      *
      *@ param inputfilepath import excel file path
      *@ param outputfilepath export PDF file path
      */
     public static void jacobExcelToPDF(String inputFilePath, String outputFilePath) {
         ActiveXComponent ax = null;
         Dispatch excel = null;
 ​
         try {
             ComThread.InitSTA();
             ax = new ActiveXComponent("Excel.Application");
             ax.setProperty("Visible", new Variant(false));
		 	//Disable macros
             ax.setProperty("AutomationSecurity", new Variant(3));
 ​
             Dispatch excels = ax.getProperty("Workbooks").toDispatch();
 ​
             Object[] obj = {
                     inputFilePath,
                     new Variant(false),
                     new Variant(false)
             };
 ​
             excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();
 ​
 			//Conversion format
             Object[] obj2 = {
                     //Pdf format equals 0
                     new Variant(0),
                     outputFilePath,
                     //0 = standard (the generated PDF image will not be blurred), 1 = smallest file
                     new Variant(0)
             };
 ​
             Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, obj2, new int[1]);
 ​
         } catch (Exception e) {
             e.printStackTrace();
             throw e;
         } finally {
             if (excel != null) {
                 Dispatch.call(excel, "Close", new Variant(false));
             }
             if (ax != null) {
                 ax.invoke("Quit", new Variant[]{});
                 ax = null;
             }
             ComThread.Release();
         }
 ​
 ​
     }

The above are the two most commonly used methods for exporting Excel to PDF in Java. The second method is recommended!

I’m the grey ape. I’ll see you next time!