【JAVA】 将csv格式文件转换为pdf格式文件

发布时间 2023-08-11 10:32:17作者: 独孤无绝
public void csvtopdf ( ) {
    String csvFilePath = "E:/tmp/output.csv";
    String pdfFilePath = "E:/tmp/outputPdf.pdf";

try { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath)); document.open(); BufferedReader csvReader = new BufferedReader(new FileReader(csvFilePath)); String row;
        BaseFont baseFont
= BaseFont.createFont("simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //中文字体,解决转换后的pdf文件无法显示中文的问题,从window默认字体文件库中复制到项目中即可 Font font = new Font(baseFont, 12, Font.NORMAL); while ((row = csvReader.readLine()) != null) { String[] data = row.split(","); PdfPTable table = new PdfPTable(data.length); table.setWidthPercentage(100); for (String cell : data) { Phrase phrase = new Phrase(cell.replaceAll("\"", ""), font); System.out.println(phrase); PdfPCell pdfCell = new PdfPCell(phrase); pdfCell.setHorizontalAlignment(Element.ALIGN_CENTER); pdfCell.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(pdfCell); } document.add(table); document.add(Chunk.NEWLINE); } csvReader.close(); document.close(); System.out.println("PDF created successfully!"); } catch (Exception e) { e.printStackTrace(); } }