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

技术 selenium + thymeleaf + itextpdf + chromedriver

使用thymeleaf 将动态数据替换

使用selenium +chromedriver 进行js ,css等逻辑运算后渲染视图

使用itextpdf 将html 转为pdf 文件

html模板

xml 复制代码
<!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>

执行代码

java 复制代码
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 URL
            htmlContent = "data:text/html;base64," + base64EncodedHtmlContent;
            // 加载HTML内容
//            htmlContent = "data:text/html;charset=utf-8," + encodedHtmlContent;

            driver.get(htmlContent);

            // 等待JavaScript执行完成
            Thread.sleep(3000); // 等待3秒,确保JavaScript执行完成

            //获取全部的html
            String 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 依赖

xml 复制代码
		<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>
相关推荐
2301_768350232 小时前
Vue第二期:组件及组件化和组件的生命周期
前端·javascript·vue.js
华洛3 小时前
公开一个AI产品的商业逻辑与设计方案——AI带来的涂色卡自由
前端·后端·产品
明远湖之鱼3 小时前
opentype.js 使用与文字渲染
前端·svg·字体
90后的晨仔4 小时前
Vue 3 组合式函数(Composables)全面解析:从原理到实战
前端·vue.js
今天头发还在吗4 小时前
【React】动态SVG连接线实现:图片与按钮的可视化映射
前端·javascript·react.js·typescript·前端框架
小刘不知道叫啥4 小时前
React 源码揭秘 | suspense 和 unwind流程
前端·javascript·react.js
szial4 小时前
为什么 React 推荐 “不可变更新”:深入理解 React 的核心设计理念
前端·react.js·前端框架
mapbar_front4 小时前
面试是一门学问
前端·面试
90后的晨仔5 小时前
Vue 3 中 Provide / Inject 在异步时不起作用原因分析(二)?
前端·vue.js
90后的晨仔5 小时前
Vue 3 中 Provide / Inject 在异步时不起作用原因分析(一)?
前端·vue.js