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

批量生成不同用户的pdf 文件(html样式)

技术 selenium + thymeleaf + itextpdf + chromedriver
使用thymeleaf 将动态数据替换
使用selenium +chromedriver 进行js ,css等逻辑运算后渲染视图
使用itextpdf 将html 转为pdf 文件

html模板

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>My Page</title><!-- 引入 jQuery 库 --><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script><style>body {font-family: 'SimSun', 'SimHei', sans-serif;}</style><!-- 引入 G2 库 -->
<!--    <script src="https://gw.alipayobjects.com/os/lib/antv/g2/4.1.16/dist/g2.min.js"></script>-->
</head>
<body>
<h1 th:text="${title}">cser</h1>
<div id="content"></div>
<script type="text/javascript" th:inline="javascript">/*<![CDATA[*/document.addEventListener('DOMContentLoaded', function() {$('#content').html("<select name='status'>"+"   <option value='测试'>111</option>"+"   <option value='测试2'>222</option>"+"</select>")let titlenew = "测试"; // 确保这里赋值正确document.querySelector('h1').innerText = titlenew;document.title = titlenew; // 更新浏览器标签页的标题});/*]]>*/
</script></body>
</html>

执行代码

public void generatePdf(HttpServletResponse response) throws IOException {// 设置 ChromeDriver 路径// 设置 ChromeDriver 路径System.setProperty("webdriver.chrome.driver", "D:/chromedriver.exe");// 初始化 WebDriver// 设置chrome选项ChromeOptions options = new ChromeOptions();
//        options.setBinary("D:\\chromedriver\\chrome/chrome.exe");options.setBinary("C:\\Chrome\\Application/chrome.exe");options.addArguments("--headless");options.addArguments("--disable-gpu");WebDriver driver = new ChromeDriver(options);// 动态数据Map<String, Object> data = new HashMap<>();data.put("title", "Hello, World!");data.put("condition", "true");
//        data.put("imagePath", imagePath); // 路径// 使用 Thymeleaf 渲染模板Context context = new Context();context.setVariables(data);String htmlContent = templateEngine.process("templates", context);try {driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(60));// 将 htmlContent 进行 Base64 编码byte[] base64EncodedBytes = Base64.getEncoder().encode(htmlContent.getBytes(StandardCharsets.UTF_8));String base64EncodedHtmlContent = new String(base64EncodedBytes);// 构建完整的 data URLhtmlContent = "data:text/html;base64," + base64EncodedHtmlContent;// 加载HTML内容
//            htmlContent = "data:text/html;charset=utf-8," + encodedHtmlContent;driver.get(htmlContent);// 等待JavaScript执行完成Thread.sleep(3000); // 等待3秒,确保JavaScript执行完成//获取全部的htmlString pageSource = driver.getPageSource();
//            // 获取最终的HTML内容
//            WebElement body = driver.findElement(By.tagName("html"));
//            String renderedHtml = body.getAttribute("outerHTML");try (FileOutputStream outputStream = new FileOutputStream(filePath)) {// 使用字体文件路径创建字体对象String fontPath = "chromedriver/cs.TTF";FontProgram font = FontProgramFactory.createFont(fontPath);// 创建 DefaultFontProvider 并设置字体DefaultFontProvider fontProvider = new DefaultFontProvider(false, false, true);fontProvider.addFont(font);// 创建 ConverterProperties 并设置字体提供者ConverterProperties converterProperties = new ConverterProperties();converterProperties.setFontProvider(fontProvider);HtmlConverter.convertToPdf(pageSource, outputStream, converterProperties);} catch (Exception e) {e.printStackTrace();}} catch (InterruptedException e) {driver.close();}}

pom 依赖

		<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java --><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-java</artifactId><version>4.27.0</version></dependency><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-chrome-driver</artifactId><version>4.27.0</version> <!-- 确保与 selenium-java 版本一致 --></dependency><!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-remote-driver --><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-remote-driver</artifactId><version>4.27.0</version></dependency><!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-api --><dependency><groupId>org.seleniumhq.selenium</groupId><artifactId>selenium-api</artifactId><version>4.27.0</version></dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.11</version></dependency>
http://www.lryc.cn/news/494476.html

相关文章:

  • 混淆零碎知识点
  • 排序算法2
  • 【Web开发基础学习——corsheaders 应用的理解】
  • Redis和MySQL之间如何进行数据同步
  • css:转换
  • 状态管理与存储:Vuex 和 sessionStorage
  • Redis和MySQL保持一致性的延迟双删(Delay Double Delete)策略
  • 快速理解微服务中Fegin的概念
  • 新增工作台模块,任务中心支持一键重跑,MeterSphere开源持续测试工具v3.5版本发布
  • 快速搭建一个博客!!!“Halo框架深度优化:搭建你的个性化博客或网站”
  • 009 STM32 HAL库介绍
  • 【微服务】 Eureka和Ribbon
  • 6.算法移植第六篇 YOLOV5/rknn生成可执行文件部署在RK3568上
  • element的el-table表格标题用css自定义是否必填,用添加伪类的方式标红色*
  • 数据仓库: 8- 数据仓库性能优化
  • 可编程网络在分布式深度学习通信瓶颈控制中的应用与未来展望
  • 【论文笔记】Tool Learning with Foundation Models 论文笔记
  • Springfox迁移到 Springdoc OpenAPI 3
  • DIY-Tomcat part 3 实现对动态资源的请求
  • 3.10 内核 BUG_ON() at xfs_vm_writepage() -> page_buffers()
  • CrystalDiskInfo:硬盘健康监测工具简介和下载
  • Flink cdc同步增量数据timestamp字段相差八小时(分析|解决)不是粘贴复制的!
  • 【docker】9. 镜像操作与实战
  • js-显示转换(强制转换)与隐式转换,==与===区别
  • 【通俗理解】步长和学习率在神经网络中是一回事吗?
  • 【PTA】【数据库】【SQL命令】编程题2
  • Spring Boot林业产品推荐系统:用户指南
  • 【Conda 】Conda 配置文件详解:优化你的包管理与环境设置
  • win10中使用ffmpeg的filter滤镜
  • 设计模式 外观模式 门面模式