Convert CSV to PDF in Java
A CSV file is a plain text file containing only numbers and letters. Due to its wide compatibility, this file format is often used to transfer tabular data between programs and databases. This article will share how to programmatically convert a CSV file to PDF using a free Java API.
Import Dependency (2 Methods)
1# Download the free API (Free Spire.XLS for Java) and unzip it, then add the Spire.Xls.jar file to your project as dependency.
2# Directly add the jar dependency to maven project by adding the following configurations to the pom.xml.
<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.free</artifactId>
<version>5.1.0</version>
</dependency>
</dependencies>
Sample Code
It's quite simple to convert a CSV file to PDF using the free API, and the complete sample code is shown as below.
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("input.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");
}
}