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");
        }
//...
相关推荐
এ慕ོ冬℘゜17 小时前
html理论
前端·html
是立不是利18 小时前
HTML 的尊严:一种被低估的语言
前端·html
anOnion19 小时前
构建无障碍组件之Landmarks Pattern
前端·html·交互设计
鲲穹AI种草1 天前
PDF 文档多格式转换处理,多款 PDF 处理工具能力客观记录
pdf·文档格式转换
xy34531 天前
Axure9.0中继器遮罩实现方法
前端·ui·html·axure·原型·产品设计
Felicia-侧听1 天前
PDF怎么转换成OFD?在线PDF转OFD方法
pdf·pdf转换·ofd·电子发票·文件格式转换·pdf转ofd·ofd格式
大梦想家a2 天前
基于 HTML+CSS 的个人生活主页设计与实现
css·html·生活
雪芽蓝域zzs2 天前
第二十七节:进阶:路由权限控制 + 404 / 401 全局异常页面开发
前端·javascript·html
平头哥技术团队2 天前
Day 10 | 工欲善其事:VS Code 配置与项目归档
android·开发语言·前端·javascript·html·交互
开开心心_Every2 天前
实现鼠标键盘动作录制与重复播放的工具
微信·jupyter·pycharm·pdf·计算机外设·word·excel