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");
        }
//...
相关推荐
随手工具-Excel, pdf, SQL5 小时前
多个 PDF 怎么合并成一个?免费在线工具,还能混入图片和 Word
pdf·word·效率工具·在线工具·pdf合并·合并pdf
2601_965912835 小时前
PDF加水印工具实测:2026年国内免费方案对比
pdf
AmyLin_20018 小时前
PDF 色彩保真工程实践【3】上手实践:工程结构、依赖集成与一键构建运行
c++·visualstudio·pdf·zlib·vcpkg·libtiff·cmyk
2601_965912839 小时前
PDF转Word技术选型:2026年文档解析引擎性能对比与集成评估
pdf·word
weipt9 小时前
springboot项目运行的几种方式
javascript·css·html
鸿翼Macrowing1 天前
**从一份 PDF 到一次 API 调用:企业 AI 能力的“最后一公里“**
人工智能·pdf·agent·数据治理·skill
呼噜想睡觉1 天前
Flex弹性布局
css·html·css3
工具派1 天前
发PDF给外部前先做脱敏:我用在线工具批量涂黑了身份证号和姓名(实操记录)
pdf
AI行业学习1 天前
Claude Code + cc-switch + Git + Node.js 全套下载+安装+配置完整版
开发语言·git·python·前端框架·node.js·html·notepad++
南风微微吹1 天前
【英一】考研英语一历年真题及答案解析PDF(1980-2026年)
考研·pdf