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");
        }
//...
相关推荐
凌云若寒4 小时前
BarTender许可 | 关于PDF打印数量说明
学习·pdf·产品经理·制造·软件需求
进击切图仔4 小时前
RAG 加载 pdf 文档
linux·前端·pdf
向阳而生6604 小时前
iframe 使用全解析:语法、避坑与实操指南(新手友好)
html
优化控制仿真模型5 小时前
30套高级毕业答辩ppt模版(免费下载)
经验分享·pdf
XMJ20026 小时前
解决包含visio图的Word文档转PDF后部分文字消失问题的一种方法
pdf·word
daanpdf7 小时前
TED演讲稿中英文对照pdf合集100篇
pdf
w2018007 小时前
巴菲特致股东的信PDF汇总(英文版原文+中文翻译)
pdf
优化控制仿真模型7 小时前
【2026】新高考英语大纲词汇表3500个电子版PDF(含正序版、乱序版和默写版)
经验分享·pdf
钝挫力PROGRAMER7 小时前
复杂PDF转Markdown实战:从Marker到多模态的处理全记录
python·pdf
a1117767 小时前
细胞结构实验室(react 开源)
前端·javascript·开源·html