Java: Convert CSV to PDF

A CSV file is essentially a plain text file. It can be easily edited by almost any program that can handle text files, such as Notepad. Converting a CSV file to PDF can help in preventing it from being edited by viewers. In this article, you will learn how to convert CSV to PDF in Java using Spire.XLS for Java.

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

Convert CSV to PDF in Java

The following are the steps to convert a CSV file to PDF:

  • Create an instance of Workbook class.
  • Load the CSV file using Workbook.loadFromFile(filePath, separator) method.
  • Set the worksheet to be rendered to one PDF page using Workbook.getConverterSetting().setSheetFitToPage(true) method.
  • Get the first worksheet in the Workbook using Workbook.getWorksheets().get(0) method.
  • Loop through the columns in the worksheet and auto-fit the width of each column using Worksheet.autoFitColumn() method.
  • Save the worksheet to PDF using Worksheet.saveToPdf() method.
  • Java
import com.spire.xls.Workbook;
import com.spire.xls.Worksheet;

public class ConvertCsvToPdf {
    public static void main(String []args) {
        //Create a Workbook instance
        Workbook wb = new Workbook();
        //Load a CSV file
        wb.loadFromFile("Sample.csv", ",");

        //Set SheetFitToPage property as true to ensure the worksheet is converted to 1 PDF page
        wb.getConverterSetting().setSheetFitToPage(true);

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

        //Loop through the columns in the worksheet
        for (int i = 1; i < sheet.getColumns().length; i++)
        {
            //AutoFit columns
            sheet.autoFitColumn(i);
        }

        //Save the worksheet to PDF
        sheet.saveToPdf("toPDF.pdf");
    }
}

Java: Convert CSV 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.