当前位置: 首页 > article >正文

Thymeleaf模板引擎生成的html字符串转换成pdf

依赖引入
 	 implementation("org.springframework.boot:spring-boot-starter-thymeleaf")
     implementation("org.xhtmlrenderer:flying-saucer-pdf")

将ITemplateEngine注入到spring管理的类中,

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");
        }
//...

http://www.kler.cn/a/405463.html

相关文章:

  • 理论结合实践:用Umami构建网站分析系统
  • 什么是计算机网络
  • 关于SpringBoot集成Kafka
  • 【系统设计】设计一个系统时,需要考虑的关键因素
  • Vue3中的祖孙组件通信——provideinject
  • centos7.9搭建k8s集群
  • [数组双指针] 0345. 反转字符串中的元音字母
  • 区号查询免费API接口教程
  • 提成制是什么?如何高效管理提成制?
  • useEffect、useCallback、useMemo和memo的区别
  • PDF 转 HTML API 数据接口
  • 数据库事务及其原理
  • shell脚本启动springboot项目
  • vscode利用ofExtensions插件可以调试单进程Openfoam,但是不能调试mpi多进程案例
  • “软件定义汽车”时代 | 产线海量数据刷写解决方案
  • 【Spark】【大数据技术基础】课程 实验七 Spark基础编程实验
  • Linux|进程程序替换
  • 【PGCCC】B+Tree 的并发优化 BLink-Tree
  • 解锁电商新境界:1688 API接口实战指南——商品详情与关键字搜索全攻略
  • 神经网络12-Time-Series Transformer (TST)模型