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");
        }
//...
相关推荐
南风微微吹1 天前
2015-2025年英语四级历年真题及答案解析电子版PDF(含听力音频)
pdf·英语四级
Revio Lab1 天前
把 AI 生成的 HTML 当 Markdown 来管:Web-Doc 自托管文档站实践
前端·html·mcp·html文档
Metaphor6921 天前
使用 Python 将 Excel 转换为 PDF
python·pdf·excel
daanpdf1 天前
考研英语一历年真题及答案解析PDF(2010-2026)百度网盘
考研·pdf
daanpdf1 天前
历年考研数学一、数学二、数学三真题试卷及答案PDF
考研·pdf
南风微微吹1 天前
2026年初级社会工作者考试历年真题及答案解析PDF电子版(2010-2025年)
pdf
俊哥工具1 天前
不用安装不收费!多功能U盘修复工具,解决大部分U盘故障
学习·pdf·word·excel·音视频
之歆1 天前
DAY_14JavaScript DOM 进阶:HTML DOM 接口、事件监听与经典交互实战
开发语言·前端·javascript·html·ecmascript·交互
ZC跨境爬虫1 天前
跟着 MDN 学 HTML day_64:从 object 到 iframe 的嵌入技术全面解析
开发语言·前端·javascript·ui·html·音视频