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(); } }
标签:document,JAVA,String,BaseFont,格式文件,pdfCell,new,csv From: https://www.cnblogs.com/z-Z-/p/17622394.html