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");
        }
//...
相关推荐
lightqjx12 分钟前
【前端】前端学习一之HTML从入门到精通
前端·学习·html
2501_943610362 小时前
我爱导航系统美化版源码网址导航系统带后台-【全开源】
前端·后端·html·php
我命由我123453 小时前
React - 路由样式丢失问题、路由观察记录、路由传递参数
开发语言·前端·javascript·react.js·前端框架·html·ecmascript
EliseL3 小时前
SuperMap iClient3D for WebGL 如何实时汇报相机位置天气情况
javascript·3d·html·webgl
开开心心就好4 小时前
电子教材下载工具,支持多链接批量下载
windows·随机森林·计算机视觉·pdf·计算机外设·逻辑回归·excel
rosmis5 小时前
自动化文献检索与下载工作流 (Phase 3 逻辑树)
python·pdf·自动化
将心ONE5 小时前
烟花绽放效果
html
南风微微吹5 小时前
考研数学一、二、三历年真题及答案解析PDF电子版(1987-2026年)
考研·pdf
D_C_tyu5 小时前
HTML | 结合Canvas开发具有智能寻路功能的贪吃蛇小游戏实战详解
javascript·算法·游戏·html·bfs
南风微微吹5 小时前
2009-2025年英语专业四级历年真题及答案解析电子版PDF(专四)
pdf·英语专业四级