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");
        }
//...
相关推荐
软件技术NINI4 小时前
html css js网页制作成品——化妆品html+css+js (7页)附源码
javascript·css·html
小白64029 小时前
前端梳理体系从常问问题去完善-框架篇(react生态)
前端·css·html·reactjs
2501_9291576810 小时前
FC和SFC的原版说明书(扫描的PDF)
pdf
又是忙碌的一天21 小时前
前端学习day01
前端·学习·html
不会算法的小灰1 天前
HTML简单入门—— 基础标签与路径解析
前端·算法·html
cooldream20091 天前
深度解析中秋节HTML5动画的实现
前端·html·html5
zhangfeng11331 天前
R 导出 PDF 时中文不显示 不依赖 showtext** 的最简方案(用 extrafont 把系统 TTF 真正灌进 PDF 内核)
开发语言·r语言·pdf·生物信息
我登哥MVP1 天前
HTML-CSS-JS-入门学习笔记
javascript·css·笔记·学习·html
pc大老1 天前
PDF文件翻译新方法:轻松多语言转换!
pdf·pdf文件·#pdf设置·pdf转换多国语言
水冗水孚1 天前
React中使用map+area标签实现img图片特定区域标记功能(可用Photoshop精准拾取对应点位)
react.js·html·photoshop