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");
        }
//...
相关推荐
不考研当牛马3 小时前
HTML CSS 新手大全初学者必看 (含有部分 JavaScript)
javascript·css·html
2501_906467636 小时前
html5网页中如何实现内网大文件的加密下载?
前端·html·html5·vue上传解决方案·vue断点续传·vue分片上传下载·vue分块上传下载
2501_930707787 小时前
使用C#代码为 PDF 文档添加印章
pdf
daanpdf8 小时前
C1C2驾照考试科目一题库和答案大全免费版下载2026
pdf
开开心心就好9 小时前
吾爱大佬原创的文件时间修改工具
安全·智能手机·pdf·电脑·智能音箱·智能手表·1024程序员节
ZC跨境爬虫9 小时前
跟着 MDN 学 HTML day_25:(数字音频概念完全解析)
前端·ui·html·edge浏览器·媒体
开开心心_Every9 小时前
安卓免费证件照制作软件,无广告弹窗
linux·运维·服务器·安全·elasticsearch·zookeeper·pdf
优化控制仿真模型1 天前
【2026】新大纲普通话考试真题题库50套(PDF电子版)
经验分享·pdf
摇滚侠1 天前
11 空间转换 前端 Web 开发 HTML5 + CSS3 + 移动 web 视频教程,前端web入门首选黑马程序员
前端·css·html·css3·html5
小李子呢02111 天前
前端八股CSS---CSS布局
css·html·css3