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");
        }
//...
相关推荐
云月呀13 小时前
《死亡回忆录》藏汉双语版电子版 PDF,穆迪博士 150 例濒死体验访谈,一部关于生死的温柔读本
pdf·死亡回忆录
zhippt_101413 小时前
教师做课件太耗时?AI生成PPT工具与图转PPT实测梳理
人工智能·html·powerpoint
winfredzhang15 小时前
从零手写一个毛玻璃风格的页面搭建台:单文件 HTML 实现组件放置、面板磁吸与图层管理
前端·html
xiaolinudao1231 天前
给pdf文件盖骑缝章的软件有哪些
pdf
沫璃染墨1 天前
从零入门计算机网络系列(十一):HTTP协议进阶——从重定向原理到GET/POST与Fiddler抓包
linux·服务器·开发语言·网络·c++·tcp/ip·html
hu55667981 天前
如何使用Adobe Acrobat Pro DC将1页PDF切割为2页,A3变A4打印。
pdf
ComPDFKit1 天前
PDF转Word后,每行都成一段?先分清断段、文本框和扫描页
pdf·word
前端架构师-老李2 天前
HTML与CSS基础第五课—HTML的空格、换行、横线相关知识
前端·css·html
echome8882 天前
CSS 布局:Flex 和 Grid 怎么选,附常见坑
前端·css·html
Nymph_Zhu2 天前
pdf转换markdown预览及内容互相点击定位
前端·pdf·vue3·markdown·element-plus