|
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; |
|
} |
|
} |