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");
        }
//...
相关推荐
XLYcmy13 小时前
pdf论文处理:CSV输出模式
数据库·python·pycharm·pdf·论文·csv·dify
jackyrongvip13 小时前
开源一个可以把HTML敏感词替换的页面小工具
开源·html·敏感词·ai脱敏
@Mike@1 天前
HTML核心知识点笔记
前端·笔记·html
IMPYLH1 天前
HTML 的 <figcaption> 元素
前端·html
IMPYLH2 天前
HTML 的 <figure> 元素
前端·javascript·html
SamChan902 天前
用Python+Requests批量翻译PDF:从脚本到调度
后端·python·microsoft·ai·pdf·机器翻译
SamChan902 天前
PDF翻译API的JWT签名鉴权与速率限制设计:安全实战指南
网络·安全·pdf
richdata2 天前
动态OTB vs 静态OTB:鞋服零售该选哪种管理模式?
前端·html·零售
Web打印2 天前
gridreport导出后的pdf只支持①到⑨,然而⑩之后的不支持_gwj_20260811_122323.docx
pdf
AmyLin_20012 天前
PDF 脱敏技术【1】:PDF 脱敏不是盖黑框:为什么敏感信息仍能被复制,正确的保护方式是什么?
安全·pdf·sdk·脱敏·文档安全·pdf 脱敏·智能脱敏