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");
        }
//...
相关推荐
志尊宝21 小时前
Vue3 零基础每日笔记(055):组件里正确使用 store——storeToRefs 解构与 $patch 批量修改
笔记·vue·html·前端开发·软件开发
huaweichenai21 小时前
spring boot操作PDF
java·spring boot·pdf
吴声子夜歌1 天前
HTML——看似普通的元素的背后(<a>标签)
html
IMPYLH1 天前
HTML 的 <style> 元素
前端·html
刃神太酷啦1 天前
前端入门第一课:HTML 基础语法 + 常用标签 + 实战全解
服务器·c语言·前端·javascript·css·c++·html
IMPYLH1 天前
HTML 的 <strong> 元素
前端·html
开开心心就好1 天前
批量提取PDF中的图片,直接导出原图
前端·javascript·支持向量机·智能手机·pdf·html·启发式算法
我命由我123452 天前
CSS - CSS 媒体查询 orientation
前端·javascript·css·html·css3·html5·js
咩咩啃树皮2 天前
ES6 Set 核心特点 + 最简数组去重
前端·javascript·html
zhanghaha13142 天前
HTML系列教程:18_HTML / CSS 颜色零基础详解
css·html·tensorflow