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");
        }
//...
相关推荐
2601_967760786 小时前
2026年PDF压缩与页码添加工具技术实测:性能、算法与本地化适配深度对比
算法·pdf
EatFan9 小时前
HTML前端利用flex解决input定位的问题
前端·css·html·css3
labixiong13 小时前
告别scroll 监听:CSS 滚动驱动动画,主线程堵死也仍跟手
前端·css·html
weixin_4508135314 小时前
pdf文档转为markdown文档
linux·pdf
曲无忆14 小时前
体脂率计算器HTML实现
html
慧都小妮子14 小时前
用 Python 批量把 PDF 参考文献排成 MLA 格式:Spire.Doc for Python 实战
python·pdf·c#·spire.doc·mla格式·参考文献排版·pdf批量处理
weixin_4935036718 小时前
商会系统里的在线文件预览:PDF/Word/Excel 三种实现与选型(Node + 前端实战)
pdf·word·excel
King of fraud19 小时前
HTML 页面的 CSS 选择器详解
前端·css·html
蜡台19 小时前
Vue 3 原生 ESM 开发实战:不用打包工具,从零搭建组件化应用
前端·javascript·vue.js·html
ygwelcome19 小时前
视频收割机-VideoHarvester架构功能介绍
pdf·音视频