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");
        }
//...
相关推荐
JackieDYH2 小时前
HTML+CSS+JavaScript实现图像对比滑块demo
javascript·css·html
月巴月巴白勺合鸟月半11 小时前
几种 HTML 转 PDF的方式
pdf·c#
冥界摄政王14 小时前
Cesium学习第二章 camera 相机
node.js·html·vue3·js·cesium
韩曙亮14 小时前
【Web APIs】移动端轮播图案例 ( 轮播图自动播放 | 设置无缝衔接滑动 | 手指滑动轮播图 | 完整代码示例 )
前端·javascript·css·html·轮播图·移动端·web apis
PieroPc16 小时前
Html +css+js 写的一个小商城系统(POS系统)
javascript·css·html
顾安r16 小时前
1.1 脚本网页 战推棋
java·前端·游戏·html·virtualenv
Channing Lewis1 天前
Python读取excel转成html,并且复制excel中单元格的颜色(字体或填充)
python·html·excel
夏日白云1 天前
《PDF解析工程实录》第 12 章|别让模型贴着墙走:为什么加一圈空白,效果反而更好?
图像处理·机器学习·pdf·llm·大语言模型·rag·文档解析
0思必得01 天前
[Web自动化] Requests模块基本使用
运维·前端·python·自动化·html·web自动化
代码游侠1 天前
学习笔记——HTML网页开发基础
运维·服务器·开发语言·笔记·学习·html