使用的依赖
<dependency> <groupId>com.itextpdf</groupId> <artifactId>html2pdf</artifactId> <version>3.0.5</version> </dependency>
获取读取文件并转为PDF
//读取html文件内容 File file = new File("D:\\Administrator\\Pictures\\output.html"); StringBuilder stringBuilder = new StringBuilder(); FileInputStream fileInputStream = new FileInputStream(file); int len = 0; byte[] buffer = new byte[1024]; while(-1!=(len=fileInputStream.read(buffer))) { stringBuilder.append(new String(buffer,0,len)); } String html = stringBuilder.toString(); //文件地址路径 String fontPath = "C:\\Windows\\Fonts\\simsun.ttc,0"; //pdf文件路径 String pdfPath = "D:\\test.pdf"; FileOutputStream fileOutputStream = new FileOutputStream(pdfPath); PdfWriter pdfWriter = new PdfWriter(fileOutputStream); PdfDocument pdfDocument = new PdfDocument(pdfWriter); //设置纸张大小 pdfDocument.setDefaultPageSize(PageSize.A4); //添加中文字体支持 ConverterProperties properties = new ConverterProperties(); FontProvider fontProvider = new FontProvider(); fontProvider.addFont(fontPath); properties.setFontProvider(fontProvider); // 生成pdf文档 HtmlConverter.convertToPdf(html,pdfWriter,properties); pdfWriter.close();
标签:pdfWriter,String,stringBuilder,html,fontProvider,Itext,HTML,PDF,new From: https://www.cnblogs.com/sun-in-sky/p/17836349.html