From excel to pdf java

В последнее время мне нужно отправить файл Excel моему бизнес-партнеру и не хочу, чтобы он просматривал или изменял важные формулы, поэтому я решил преобразовать файл Excel в PDF. В этой статье я поделюсь своим опытом о том, как конвертировать Excel в PDF в приложении Java с помощью Free Spire.XLS for Java:

Способ 1: преобразовать всю книгу Excel в PDF.
Способ 2: конвертировать один лист Excel в PDF.

Конфигурация среды

Установите пакет jar через репозиторий Maven, и код для настройки файла 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>

Тестовый документ Excel, включающий две таблицы:

image

Пример 1 :преобразовать всю книгу Excel в PDF.

import com.spire.xls.*; 
public class ExcelToPDF { 
     public static void main(String[] args) { 

          //Загрузить файл примера Excel
          Workbook workbook = new Workbook();
          workbook.loadFromFile("Sample.xlsx"); 

          //По размеру страницы
          workbook.getConverterSetting().setSheetFitToPage(true); 

          //Сохранить как PDF документ
          workbook.saveToFile("ExcelToPDF.pdf",FileFormat.PDF);
     }
 }

image

Пример 2: конвертировать один лист Excel в PDF.

import com.spire.xls.*; 
public class ExcelToPDF { 
     public static void main(String[] args) { 

          //Загрузить файл примера Excel
          Workbook workbook = new Workbook();
          workbook.loadFromFile("Sample.xlsx"); 

          //Получить второй лист
          Worksheet worksheet = workbook.getWorksheets().get(1); 

          //Сохранить как PDF документ
          worksheet.saveToPdf("ToPDF2.pdf");
     }
 }

image

Add on to assylias’s answer

The code from assylias above was very helpful to me in solving this problem. The answer from santhosh could be great if you don’t care about the resulting PDF looking exactly like your excel pdf export would look. However, if you are, say, filling out an excel template using Apache POI an then trying to export that while preserving its look and not writing a ton of code in iText just to try to get close to that look, then the VBS option is quite nice.

I’ll share a Java version of the kotlin assylias has above in case that helps anyone. All credit to assylias for the general form of the solution.

In Java:

try {
    //create a temporary file and grab the path for it
    Path tempScript = Files.createTempFile("script", ".vbs");

    //read all the lines of the .vbs script into memory as a list
    //here we pull from the resources of a Gradle build, where the vbs script is stored
    System.out.println("Path for vbs script is: '" + Main.class.getResource("xl2pdf.vbs").toString().substring(6) + "'");
    List<String> script = Files.readAllLines(Paths.get(Main.class.getResource("xl2pdf.vbs").toString().substring(6)));

    // append test.xlsm for file name. savePath was passed to this function
    String templateFile = savePath + "\test.xlsm";
    templateFile = templateFile.replace("\", "\\");
    String pdfFile = savePath + "\test.pdf";
    pdfFile = pdfFile.replace("\", "\\");
    System.out.println("templateFile is: " + templateFile);
    System.out.println("pdfFile is: " + pdfFile);

    //replace the placeholders in the vbs script with the chosen file paths
    for (int i = 0; i < script.size(); i++) {
        script.set(i, script.get(i).replaceAll("XL_FILE", templateFile));
        script.set(i, script.get(i).replaceAll("PDF_FILE", pdfFile));
        System.out.println("Line " + i + " is: " + script.get(i));
    }

    //write the modified code to the temporary script
    Files.write(tempScript, script);

    //create a processBuilder for starting an operating system process
    ProcessBuilder pb = new ProcessBuilder("wscript", tempScript.toString());

    //start the process on the operating system
    Process process = pb.start();

    //tell the process how long to wait for timeout
    Boolean success = process.waitFor(timeout, minutes);
    if(!success) {
        System.out.println("Error: Could not print PDF within " + timeout + minutes);
    } else {
        System.out.println("Process to run visual basic script for pdf conversion succeeded.");
    }
    
} catch (Exception e) {
    e.printStackTrace();
    Alert saveAsPdfAlert = new Alert(AlertType.ERROR);
    saveAsPdfAlert.setTitle("ERROR: Error converting to pdf.");
    saveAsPdfAlert.setHeaderText("Exception message is:");
    saveAsPdfAlert.setContentText(e.getMessage());
    saveAsPdfAlert.showAndWait();  
}

VBS:

Option Explicit
Dim objExcel, strExcelPath, objSheet

strExcelPath = "XL_FILE"


Set objExcel = CreateObject("Excel.Application")
objExcel.WorkBooks.Open strExcelPath
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)

objSheet.ExportAsFixedFormat 0, "PDF_FILE",0, 1, 0, , , 0

objExcel.ActiveWorkbook.Close
objExcel.Application.Quit

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

In this post, you’ll learn how to convert Excel files to PDFs in your Java applications using PSPDFKit’s XLSX to PDF Java API. With our API, you can convert up to 100 PDF files per month for free. All you need to do is create a free account to get access to your API key.

PSPDFKit API

Document conversion is just one of our 30+ PDF API tools. You can combine our conversion tool with other tools to create complex document processing workflows. You’ll be able to convert various file formats into PDFs and then:

  • Merge several resulting PDFs into one

  • OCR, watermark, or flatten PDFs

  • Remove or duplicate specific PDF pages

Once you create your account, you’ll be able to access all our PDF API tools.

Step 1 — Creating a Free Account on PSPDFKit

Go to our website, where you’ll see the page below, prompting you to create your free account.

Free account PSPDFKit API

Once you’ve created your account, you’ll be welcomed by the page below, which shows an overview of your plan details.

Free plan PSPDFKit API

As you can see in the bottom-left corner, you’ll start with 100 documents to process, and you’ll be able to access all our PDF API tools.

Step 2 — Obtaining the API Key

After you’ve verified your email, you can get your API key from the dashboard. In the menu on the left, click API Keys. You’ll see the following page, which is an overview of your keys:

Convert Excel to PDF Java API Key

Copy the Live API Key, because you’ll need this for the Excel to PDF API.

Step 3 — Setting Up Folders and Files

For this tutorial, you’ll use IntelliJ IDEA as your primary code editor. Next, create a new project called excel_to_pdf. You can choose any location, but make sure to select Java as the language, Gradle as the build system, and Groovy as the Gradle DSL.

Excel to PDF Java API

Create a new directory in your project. Right-click on your project’s name and select New > Directory. From there, choose the src/main/java option. Once done, create a class file inside the src/main/java folder called processor.java, and create two folders called input_documents and processed_documents in the root folder.

After that, paste your Excel file inside the input_documents folder. You can use our demo document as an example.

Your folder structure will look like this:

excel_to_pdf
├── input_documents
|    └── document.xlsx
├── processed_documents
├── src
|    └── main
|        └── java
|            └── processor.java

Step 4 — Installing Dependencies

Next, you’ll install two libraries:

  • OkHttp — This library makes API requests.

  • JSON — This library will parse the JSON payload.

Open the build.gradle file and add the following dependencies to your project:

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.2'
    implementation 'org.json:json:20210307'
}

Once done, click the Add Configuration button in IntelliJ IDEA. This will open a dropdown menu.

Excel to PDF Java API

Next, select Application from the menu:

Excel to PDF Java API

Now, fill the form with the required details. Most of the fields will be prefilled, but you need to select java 18 in the module field and add -cp excel_to_pdf.main as the main class and Processor in the field below it.

Excel to PDF Java API

To apply settings, click the Apply button.

Step 5 — Writing the Code

Now, open the processor.java file and paste the code below into it:

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import org.json.JSONArray;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public final class Processor {
    public static void main(final String[] args) throws IOException {
        final RequestBody body = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(
                        "document",
                        "document.xlsx",
                        RequestBody.create(
                                new File("input_documents/document.xlsx"),
                                MediaType.parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                        )
                )
                .addFormDataPart(
                        "instructions",
                        new JSONObject()
                                .put("parts", new JSONArray()
                                        .put(new JSONObject()
                                                .put("file", "document")
                                        )
                                ).toString()
                )
                .build();

        final Request request = new Request.Builder()
                .url("https://api.pspdfkit.com/build")
                .method("POST", body)
                .addHeader("Authorization", "Bearer YOUR_API_KEY_HERE")
                .build();

        final OkHttpClient client = new OkHttpClient()
                .newBuilder()
                .build();

        final Response response = client.newCall(request).execute();

        if (response.isSuccessful()) {
            Files.copy(
                    response.body().byteStream(),
                    FileSystems.getDefault().getPath("processed_documents/result.pdf"),
                    StandardCopyOption.REPLACE_EXISTING
            );
        } else {
            // Handle the error.
            throw new IOException(response.body().string());
        }
    }
}

ℹ️ Note: Make sure to replace YOUR_API_KEY_HERE with your API key.

Code Explanation

In the code above, you’re importing all the packages required to run the code and creating a class called processor. In the main function, you’re first creating the request body for the API call that contains all the instructions for converting the PDF. After that, you’re calling the API to process the instructions.

You’re then calling the execute() function and passing the request variable. The response of the API is then stored in the folder called processed_documents.

Output

To execute the code, click the Run button (which is a little green arrow). This is next to the field that says Processor, which is where you set the configuration.

Excel to PDF Java API

On the successful execution of the code, you’ll see a new processed file named result.pdf in the processed_documents folder.

The folder structure will look like this:

excel_to_pdf
├── input_documents
|    └── document.xlsx
├── processed_documents
|    └── result.pdf
├── src
|    └── main
|        └── java
|            └── processor.java

Final Words

In this post, you learned how to easily and seamlessly convert Excel files to PDF documents for your Java application using our Excel to PDF Java API.

You can integrate these functions into your existing applications. With the same API token, you can also perform other operations, such as merging several documents into a single PDF, adding watermarks, and more. To get started with a free trial, sign up here.

Using PDF as a format for sending documents ensures that no formatting changes will occur to the original document. Exporting Excel to PDF is a common practice in many cases. This article introduces how to convert a whole Excel document or a specific worksheet to PDF using Spire.XLS for Java.

  • Convert a Whole Excel File to PDF
  • Convert a Specific Worksheet to PDF

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>13.4.1</version>
    </dependency>
</dependencies>
    

Convert a Whole Excel File to PDF

The following are the steps to convert a whole Excel document to PDF.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Set the Excel to PDF conversion options through the methods under the ConverterSetting object, which is returned by Workbook.getConverterSetting() method.
  • Convert the whole Excel document to PDF using Workbook.saveToFile() method.
import com.spire.xls.FileFormat;
import com.spire.xls.Workbook;

public class ConvertExcelToPdf {

    public static void main(String[] args) {

        //Create a Workbook instance and load an Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("C:\Users\Administrator\Desktop\Sample.xlsx");

        //Set worksheets to fit to page when converting
        workbook.getConverterSetting().setSheetFitToPage(true);

        //Save the resulting document to a specified path
        workbook.saveToFile("output/ExcelToPdf.pdf", FileFormat.PDF);
    }
}

Java: Convert Excel to PDF

Convert a Specific Worksheet to PDF

The following are the steps to convert a specific worksheet to PDF.

  • Create a Workbook object.
  • Load a sample Excel document using Workbook.loadFromFile() method.
  • Set the Excel to PDF conversion options through the methods under the ConverterSetting object, which is returned by Workbook.getConverterSetting() method.
  • Get a specific worksheet using Workbook.getWorksheets().get() method.
  • Convert the worksheet to PDF using Worksheet.saveToPdf() method.
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ConvertWorksheetToPdf {

    public static void main(String[] args) {

        //Create a Workbook instance and load an Excel file
        Workbook workbook = new Workbook();
        workbook.loadFromFile("C:\Users\Administrator\Desktop\Sample.xlsx");

        //Set worksheets to fit to width when converting
        workbook.getConverterSetting().setSheetFitToWidth(true);

        //Get the first worksheet
        Worksheet worksheet = workbook.getWorksheets().get(0);

        //Convert to PDF and save the resulting document to a specified path
        worksheet.saveToPdf("output/WorksheetToPdf.pdf");
    }
}

Java: Convert Excel to PDF

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.

Like this post? Please share to your friends:
  • From birth to death the word
  • From autocad to word
  • From another country word
  • From and to dates in excel
  • From analysis services excel