相关jar
<!-- itext +thymeleaf html模版转pdf --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>html2pdf</artifactId> <version>5.0.1</version> </dependency> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.8.25</version> </dependency> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf</artifactId> <version>3.0.6.RELEASE</version> <scope>compile</scope> </dependency> <dependency> <groupId>net.sf.jtidy</groupId> <artifactId>jtidy</artifactId> <version>r938</version> <scope>compile</scope> </dependency>
html模版 (其中ttf文件为字体)
主要代码
/** * itext7 +thymeleaf html模版转pdf工具类 */ public class ThymeleafToPdfUtil { private static final String templateHtml = "pdf.html"; private static final String FONT = "templates/SIMHEI.TTF"; /** * contentData 模板数据 * pdfPath 生成的pdf的路径 * pdfName pdf名称 * */ public static void generatePdf(Map<String, Object> contentData,String pdfPath,String pdfName) throws Exception { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setPrefix("/templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode(HTML); templateResolver.setCharacterEncoding("UTF-8"); TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); Context context = new Context(); context.setVariable("data", contentData); String renderedHtmlContent = templateEngine.process(templateHtml, context); String xHtml = convertToXhtml(renderedHtmlContent); ConverterProperties converterProperties = new ConverterProperties(); FontProvider dfp = new DefaultFontProvider(); dfp.addFont(FontProgramFactory.createFont(ResourceUtil.readBytes(FONT))); converterProperties.setFontProvider(dfp); File destDir = new File(pdfPath); if (!destDir.exists()) { destDir.mkdirs(); } OutputStream out = new FileOutputStream(new File(pdfPath+pdfName)); HtmlConverter.convertToPdf(xHtml, out, converterProperties); System.out.print("=== pdf生成 成功 === "); } private static String convertToXhtml(String html) throws UnsupportedEncodingException { Tidy tidy = new Tidy(); tidy.setInputEncoding("UTF-8"); tidy.setOutputEncoding("UTF-8"); tidy.setXHTML(true); ByteArrayInputStream inputStream = new ByteArrayInputStream(html.getBytes("UTF-8")); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); tidy.parseDOM(inputStream, outputStream); return outputStream.toString("UTF-8"); }
}