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");
        }
//...
相关推荐
LIUAWEIO3 小时前
CSS 让鼠标呈现手型,鼠标悬浮变小手
css·html·css3·html5
ZC跨境爬虫7 小时前
跟着 MDN 学CSS day_51:支持旧浏览器的布局策略
前端·css·html·tensorflow·媒体
DFT计算杂谈10 小时前
VASP 磁性结构可视化:一键生成完美 VESTA / MCIF
java·前端·css·html·css3
2601_9611940212 小时前
2026四六级翻译预测12篇|四级六级汉译英范文PDF
pdf
2601_9611940212 小时前
2026四六级翻译预测|四级六级汉译英热点+范文PDF
pdf
绘梨衣54713 小时前
豆包Seed PDF解析企业落地方法论
大数据·python·pdf
a11177613 小时前
Aholo Viewer 3DGS渲染器 开源html
前端·html
Js_x13 小时前
HTML实现类星露谷小游戏
css·html·css3
Solis程序员14 小时前
拿捏登录安全:RS256 + 双令牌,把非法请求拦在 Redis 白名单门外
java·安全·缓存·面试·bootstrap·html
庖丁AI14 小时前
PDF解析工具怎么选?OCR、表格提取和结构化输出有什么区别
人工智能·pdf·ocr