Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created July 16, 2026 08:33
Show Gist options
  • Select an option

  • Save aspose-com-gists/ae72da524911915517950cf66f6a20d0 to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-gists/ae72da524911915517950cf66f6a20d0 to your computer and use it in GitHub Desktop.
Convert CSV to PDF in Java

Convert CSV to PDF in Java

Discover how to convert CSV to PDF in Java with Aspose.PDF for Java. This tutorial covers SDK installation, reading CSV data, creating a PDF table, and layout customization. Follow a code example and learn to fine‑tune conversion options for PDF generation.

Read the full guide here: https://blog.aspose.com/pdf/convert-csv-to-pdf-in-java/

import com.aspose.pdf.Document;
import com.aspose.pdf.Page;
import com.aspose.pdf.Table;
import com.aspose.pdf.Row;
import com.aspose.pdf.Cell;
import com.aspose.pdf.FontRepository;
import com.aspose.pdf.Font;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CsvToPdfConverter {
public static void main(String[] args) {
String csvPath = "data/input.csv";
String pdfPath = "output/Report.pdf";
// 1. Load CSV data
List<String[]> csvData = readCsv(csvPath);
// 2. Create a new PDF document
Document pdfDoc = new Document();
Page page = pdfDoc.getPages().add();
// 3. Build a table with the same number of columns as the CSV
Table table = new Table();
table.setColumnWidths("100 100 100"); // adjust as needed
// 4. Populate table rows
for (String[] rowData : csvData) {
Row row = table.getRows().add();
for (String cellText : rowData) {
Cell cell = row.getCells().add();
cell.getParagraphs().add(new com.aspose.pdf.TextFragment(cellText));
cell.setBorder(com.aspose.pdf.BorderSide.ALL, 0.5f);
}
}
// 5. Add table to the page
page.getParagraphs().add(table);
// 6. Save the PDF
pdfDoc.save(pdfPath);
System.out.println("PDF created at: " + pdfPath);
}
private static List<String[]> readCsv(String filePath) {
List<String[]> rows = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
// Simple split on comma – adjust for quoted fields if needed
rows.add(line.split(","));
}
} catch (IOException e) {
System.err.println("Error reading CSV: " + e.getMessage());
}
return rows;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment