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");
        }
//...
相关推荐
庖丁AI11 小时前
合同比对工具怎么选?Word、PDF 和扫描件差异对比思路
pdf·word
包子源12 小时前
PDF 转 Word/Excel 全链路实战:Next.js + 阿里云文档智能
pdf·word·excel
Daydream.V12 小时前
深入理解 HTML 头部底层逻辑:DOCTYPE、Meta 标签如何左右浏览器解析与渲染
前端·javascript·html
敲代码的鱼哇16 小时前
PDF 预览与签名批注写回 支持安卓 iOS 鸿蒙 UTS插件
android·ios·pdf·鸿蒙·harmony
憧憬成为web高手21 小时前
ACTF 12307复现
前端·bootstrap·html
㳺三才人子1 天前
初探 Flask
后端·python·flask·html
LaughingZhu1 天前
Product Hunt 每日热榜 | 2026-05-25
前端·人工智能·经验分享·chatgpt·html
wyc是xxs1 天前
浏览器解析HTML头部的底层逻辑
前端·html
开开心心_Every1 天前
能把网页藏在Word里的实用摸鱼工具
人工智能·科技·目标跟踪·pdf·计算机外设·语音识别·mllib
Raink老师1 天前
【AI面试临阵磨枪-64】设计多模态(文本 + 图片 + PDF)AI 助手系统
人工智能·pdf