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");
        }
//...
相关推荐
CappuccinoRose1 天前
HTML语法学习文档(五)
前端·html·html5·表单
开开心心_Every1 天前
全屏程序切换工具,激活选中窗口快速切换
linux·运维·服务器·pdf·ocr·测试用例·模块测试
开开心心就好2 天前
实用系统备份还原,小巧免PE备份快镜像小
windows·计算机视觉·pdf·计算机外设·迭代器模式·excel·桥接模式
a1117762 天前
优雅简历(html开源)
前端·开源·html
明月_清风2 天前
HTML 早已不是标签了,它现在是系统级接口:这 9 个 API 直接干翻常用 JS 库
前端·html
岱宗夫up2 天前
【前端基础】HTML + CSS + JavaScript 快速入门
前端·css·html
~央千澈~2 天前
2026 年 2 月 17 日(农历大年初一),优雅草科技正式启用最新版官网·并且依然开源代码
html
前端 贾公子2 天前
深入理解 Vue3 的 v-model 及自定义指令的实现原理(下)
前端·html
qq_24218863322 天前
3389端口内网转发概述
前端·经验分享·html
Never_Satisfied2 天前
在JavaScript / HTML中,数组查找第一个符合要求元素
开发语言·javascript·html