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");
        }
//...
相关推荐
maogewang2 小时前
清朝条约全集 PDF 电子版(三册合集):从尼布楚到辛丑,历史文献速存
pdf
maogewang4 小时前
清朝条约全集 PDF 电子版(三册合集):从尼布楚到辛丑条约的完整史料集
pdf
柒.梧.4 小时前
HTML入门指南:30分钟掌握网页基础
前端·javascript·html
木泽八7 小时前
python实现pdf拆分与合并
服务器·python·pdf
Access开发易登软件8 小时前
Access开发实战:绘制漏斗图实现业务转化分析
数据库·信息可视化·html·vba·图表·access
江上清风山间明月8 小时前
使用python将markdown文件生成pdf文件
开发语言·python·pdf
这儿有一堆花10 小时前
确保 PDF 真实性:数字签名与文档加固技术深度解析
pdf
程序员刘禹锡11 小时前
Html中常用的块标签!!!12.16日
前端·html
njsgcs11 小时前
ezdxf 打印dxf为pdf
pdf·ezdxf
缺点内向11 小时前
如何在 C# .NET 中将 Markdown 转换为 PDF 和 Excel:完整指南
pdf·c#·.net·excel