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");
        }
//...
相关推荐
shuaiqinke11 小时前
分享噪音测试分贝仪 精准测噪 数据直观超实用
pdf
scan72413 小时前
langgraphy条件边
前端·javascript·html
NiceCloud喜云15 小时前
Claude API PDF 文档问答实战:从原生解析到分页引用的完整方案
java·服务器·前端·网络·数据库·人工智能·pdf
ZC跨境爬虫20 小时前
跟着 MDN 学CSS day_9:(深入掌握CSS选择器核心技能测试)
前端·css·ui·html
姓洪的21 小时前
我用纯HTML+CSS+JS写了个全栈项目,大厂面试官追着问我这3个底层问题
html
拾年27521 小时前
别再一div到底!HTML语义化标签,拯救你的流水账代码
html·代码规范
a11177621 小时前
VR看房 网页(开源 threejs)html
前端·开源·html·vr
chéng ௹21 小时前
python将word文档转化成html
python·html·word
步十人1 天前
【JWT】验证令牌的使用
前端·bootstrap·html
ZC跨境爬虫1 天前
跟着 MDN 学CSS day_11:(深入理解CSS值与单位的完整体系)
前端·css·ui·html·tensorflow