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");
        }
//...
相关推荐
百事牛科技10 小时前
保护文档安全:PDF限制功能详解与实操
windows·pdf
前端Hardy11 小时前
HTML&CSS:高颜值产品卡片页面,支持主题切换
css·html
Never_Satisfied14 小时前
在HTML & CSS中,nth-child、nth-of-type详解
前端·css·html
你怎么知道我是队长16 小时前
前端学习---HTML---块元素和行内元素
前端·学习·html
holeer16 小时前
【V1.0】Typora 中的 HTML 支持|软件文档自翻译
前端·编辑器·html·typora·web·markdown·文档
开开心心就好17 小时前
安卓开源应用,超时提醒紧急人护独居安全
windows·决策树·计算机视觉·pdf·计算机外设·excel·动态规划
肖。354878709417 小时前
[html-1]双板块最简界面,适合用于有两个网页分发,跳转。
html
你怎么知道我是队长18 小时前
前端学习---HTML---表单
前端·学习·html
globaldomain18 小时前
立海世纪:WordPress 6.9的新功能、新模块、新API
前端·javascript·html·新媒体运营·网站建设·wordpress·域名注册
你怎么知道我是队长18 小时前
前端学习---HTML---标签属性
前端·学习·html