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");
        }
//...
相关推荐
2501_9307077815 小时前
使用C#代码在 PDF 文档中创建交互操作
pdf·c#·交互
Metaphor69215 小时前
Python 自动化办公:如何轻松在 PDF 中导入与导出表单数据
python·pdf·自动化
weixin_448771721 天前
使用Aspose给PDF添加水印
java·pdf
java1234_小锋1 天前
【技术专题】HTML5 网页技术 - HTML5 SVG
前端·html·html5
魔都吴所谓1 天前
【我的开源】Python实现一个离线 PDF 工具箱:架构、骑缝章与踩坑记录
python·pdf·开源
凯程序猿1号1 天前
SafeDRM 的视频和 PDF 如何做跨设备交付验证?
pdf·电脑
学术 学术 Fun1 天前
没有 Visio 怎样打开 VSDX?从查看、审阅到导出 PDF
pdf
五花马印务2 天前
个人书稿交付印刷前,文件格式要规范什么?(Word/PDF/ 字体 / 出血)
pdf·个人出书
指针向南2 天前
PDF转长图用什么?3种方法实测(2026)
图像处理·人工智能·计算机视觉·pdf
Data_Journal2 天前
如何使用 Python 解析 HTML
python·html