1,利用freemark 生成html
2,依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>com.itextpdf</groupId> <artifactId>html2pdf</artifactId> <version>3.0.1</version> </dependency>
3,index.ftl
<!DOCTYPE html> <html> <head> <title>Hello</title> </head> <body> This is my HTML page. <br> <h1>${user}</h1> </body> </html>
4,代码
@Autowired private Configuration configuration; @GetMapping("/pdf") public void pdf(HttpServletResponse response) throws IOException, DocumentException, TemplateException { Template template = configuration.getTemplate("index.ftl"); // 数据 Map root = new HashMap(); root.put("user", "Jack hui"); response.setContentType("application/x-download"); response.addHeader("Content-Disposition", "attachment; filename=citiesreport.pdf"); ServletOutputStream outputStream = response.getOutputStream(); StringWriter out = new StringWriter(); template.process(root, out); String html = out.toString(); HtmlConverter.convertToPdf(html, outputStream); }