Thymeleaf模板引擎生成的html字符串转换成pdf

java 复制代码
依赖引入
 	 implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
     implementation("org.xhtmlrenderer:flying-saucer-pdf")

将ITemplateEngine注入到spring管理的类中,

java 复制代码
Context context = new Context();
context.setVariable("name", wasteDisposalSiteDTO.getName());
String  processHtml= iTemplateEngine.process("hazardousWaste", context);//hazardousWaste是html模板文件路径,需要在配置文件中设置//spring:thymeleaf:prefix: classpath:/templates/ 基本路径
 //下载到浏览器
     // 设置响应类型 pdf
        response.setContentType(MediaType.APPLICATION_PDF_VALUE);

        // 设置响应编码
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.attachment()
                .filename("1" + ".pdf", StandardCharsets.UTF_8)
                .build()
                .toString());
        // 使用ByteArrayOutputStream来捕获PDF字节流
        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            // 创建ITextRenderer对象
            ITextRenderer renderer = new ITextRenderer();
            ITextFontResolver fontResolver = renderer.getFontResolver();
            ClassPathResource classPathResource = new ClassPathResource("/font/simsun.ttc");//加载字体路径,避免生成的pdf加载不出来汉字。
            fontResolver.addFont(classPathResource.getPath(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            renderer.setDocumentFromString(processHtml);
            renderer.layout();
            renderer.createPDF(os);

            // 将生成的PDF字节流写入到HTTP响应的输出流中
            response.getOutputStream().write(os.toByteArray());
            response.getOutputStream().flush();
        } catch (DocumentException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "PDF generation failed");
        }
//...
相关推荐
i紸定i19 分钟前
解决html-to-image在 ios 上dom里面的图片不显示出来
前端·ios·vue·html·html-to-image
ai.Neo21 分钟前
(第十七期)HTML图像标签详解:从入门到精通
前端·html
阿珊和她的猫22 分钟前
autofit.js: 自动调整HTML元素大小的JavaScript库
开发语言·javascript·html
Justinc.13 小时前
HTML5新增属性
前端·html·html5
挽淚14 小时前
HTML5语义化标签和“<div>的一招鲜吃遍天”
html
JuneXcy16 小时前
11.web api 2
前端·javascript·html
全栈老石21 小时前
设计师到前端不再有墙:Figma + VS Code 自动出码实践
前端·vue.js·html
全宝21 小时前
【前端特效系列】css+js实现聚光灯效果
javascript·css·html
遗悲风1 天前
html抽奖功能
前端·html
代码AI弗森1 天前
PDF OCR + 大模型:让文档理解不止停留在识字
pdf·ocr