Java + Selenium实现浏览器打印功能

Java + Selenium实现浏览器打印功能

Java调用浏览器打印功能

本文主要介绍如果通过Java实现浏览器的PDF打印功能

环境配置以及依赖导入

  1. seleniumJava依赖
xml 复制代码
      <dependency>
          <groupId>org.seleniumhq.selenium</groupId>
          <artifactId>selenium-java</artifactId>
          <version>4.41.0</version>
          <scope>compile</scope>
      </dependency>
  1. 浏览器的Driver配置(手动配置)
  • 下载不同浏览器的driver, 这里以chrome为例: https://googlechromelabs.github.io/chrome-for-testing/ 具体下载什么版本还需要看本地安装的 Chrome 的版本, 一定要版本相同, 如果没有自己对应的版本,随便选择一个下载链接,然后把版本改成自己的浏览器就行了。
txt 复制代码
### 随便选择一个
https://storage.googleapis.com/chrome-for-testing-public/146.0.7680.66/win64/chromedriver-win64.zip

### 假设我的版本为1111111.11111
https://storage.googleapis.com/chrome-for-testing-public/1111111.11111/win64/chromedriver-win64.zip
  • 导入配置
java 复制代码
// 设置Chrome浏览器的driver
System.setProperty("webdriver.chrome.driver", "C:\\PerfLogs\\chromedriver-win64\\chromedriver.exe");
  1. 通过webdrivermanager自动管理 (推荐☆☆☆☆)
  • 引入依赖:
xml 复制代码
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>6.3.3</version>
    <scope>compile</scope>
</dependency>
  • 在代码中启用
java 复制代码
// 6.3.3版本只支持以下类型的浏览器
		// chrome
        WebDriverManager.chromedriver().setup();
        // 其他使用chrome内核的浏览器
        WebDriverManager.chromiumdriver().setup();
        // firefox
        WebDriverManager.firefoxdriver().setup();
        // edge
        WebDriverManager.edgedriver().setup();
        // opera
        WebDriverManager.operadriver().setup();
        // safari
        WebDriverManager.safaridriver().setup();

设置Selenium

4.41.0版本支持的浏览器类型以及不同浏览器的配置如图所示

  1. 浏览器驱动:
  2. 浏览器配置:
这里以Chrome为例
java 复制代码
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Pdf;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.print.PageMargin;
import org.openqa.selenium.print.PageSize;
import org.openqa.selenium.print.PrintOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Base64;
import java.util.UUID;

public class PdfDownload {

    public static void main(String[] args) throws IOException {
        PdfDownload pdfDownload = new PdfDownload();
        String fileName = UUID.randomUUID().toString();
        pdfDownload.generatePdfFromUrl("http://localhost:8080/doc/xxxxxxx", "C:\\opt\\" + fileName + ".pdf");
    }

    public void generatePdfFromUrl(String url, String outputPath) throws IOException {
        // 加载chrome浏览器驱动
        System.setProperty("webdriver.chrome.driver", "C:\\PerfLogs\\chromedriver-win64\\chromedriver.exe");

        ChromeOptions options = new ChromeOptions();
        // 运行无头模式-不弹窗(服务器中必须, 本地开发可以不用)
        options.addArguments("--headless");
        // 跳过打印预览
        options.addArguments("--kiosk-printing");

        ChromeDriver driver = new ChromeDriver(options);
        try {
            driver.get(url);

            // 等待页面加载, 根据需要设置时间
            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
            wait.until(d -> (Boolean) ((JavascriptExecutor) d)
                    .executeScript("return window.jQuery ? jQuery.active == 0 : true"));
            // 等待数据渲染(1.5s), 根据需要设置时间
            Thread.sleep(1500);
            // 配置打印选项
            PrintOptions printOptions = new PrintOptions();
            printOptions.setPageSize(PageSize.ISO_A4); // A4尺寸(cm)
            printOptions.setPageMargin(new PageMargin(1.0, 1.0, 1.0, 1.0));
            printOptions.setScale(1.0);
            printOptions.setBackground(true);
            printOptions.setShrinkToFit(true);

            // 调用浏览器打印功能
            Pdf pdf = driver.print(printOptions);

            // 解码并保存文件
            byte[] pdfContent = Base64.getDecoder().decode(pdf.getContent());
            Files.write(Paths.get(outputPath), pdfContent);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            driver.quit(); // 必须关闭浏览器进程
        }
    }
}
相关推荐
Mahir085 小时前
Spring 循环依赖深度解密:从问题本质到三级缓存源码级解析
java·后端·spring·缓存·面试·循环依赖·三级缓存
影sir5 小时前
Selenium常用函数(等待)
selenium·测试工具
影sir5 小时前
Selenium常用函数(浏览器导航,文件上传,浏览器参数设置)
selenium·测试工具
RyFit6 小时前
SpringAI 常见问题及解决方案大全
java·ai
石山代码6 小时前
C++ 内存分区 堆区
java·开发语言·c++
绝知此事7 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
无风听海7 小时前
C# 隐式转换深度解析
java·开发语言·c#
一只大袋鼠7 小时前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作
java·开发语言·git
德思特8 小时前
从 Dify 配置页理解 RAG 的重要参数
java·人工智能·llm·dify·rag
YOU OU9 小时前
Spring IoC&DI
java·数据库·spring