如何在Selenium WebDriver中打印无页眉页脚的PDF?
解决Selenium Java打印PDF时去除页眉页脚的问题
核心方案:配置Chrome打印首选项
你之前尝试的isHeaderAndFooter设置需要正确嵌入Chrome的打印偏好配置中,而非单独作为启动参数。以下是修改后的Java代码,重点配置打印相关偏好:
import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.util.HashMap; import java.util.Map; public class PrintPDFWithoutHeaderFooter { public static void main(String[] args) throws InterruptedException { ChromeOptions options = new ChromeOptions(); // 配置打印偏好,禁用页眉页脚 Map<String, Object> printPreferences = new HashMap<>(); printPreferences.put("isHeaderAndFooterEnabled", false); printPreferences.put("scaling", 1.0); printPreferences.put("paperSize", "A4"); // 按需设置纸张尺寸 Map<String, Object> prefs = new HashMap<>(); prefs.put("printing.print_preview_sticky_settings.appState", printPreferences); options.setExperimentalOption("prefs", prefs); options.addArguments("--kiosk-printing"); // 保留 kiosk 打印模式 ChromeDriver driver = new ChromeDriver(options); driver.get("http://google.com"); driver.manage().window().maximize(); Thread.sleep(10000); // 获取页面标题作为PDF文件名 String pageText = driver.findElement(By.tagName("title")).getAttribute("innerHTML"); // 将标题复制到剪贴板 StringSelection stringSelection = new StringSelection(pageText); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(stringSelection, null); // 触发打印并执行AutoIT脚本 ((JavascriptExecutor) driver).executeScript("print()"); Thread.sleep(5000); try { Runtime.getRuntime().exec("src/savfiles.exe"); } catch (Exception e) { e.printStackTrace(); } driver.quit(); } }
补充方案:通过AutoIT控制打印设置窗口(若首选项配置无效)
如果上述偏好配置不生效,可能是Chrome版本或环境差异导致,可修改AutoIT脚本,在保存文件前手动关闭页眉页脚选项:
; 获取剪贴板中的标题文本 Global $sLastClip = ClipGet() ; 等待打印窗口加载 WinWait("Salvar Saída de Impressão como", "", 10) ; 打开打印更多设置面板(需用AutoIT Window Info工具确认控件ID) ControlClick("Salvar Saída de Impressão como", "", "Button3") Sleep(1000) ; 取消页眉页脚勾选(需确认复选框控件ID) ControlClick("Salvar Saída de Impressão como", "", "CheckBox1") Sleep(500) ; 聚焦文件名输入框 ControlFocus("Salvar Saída de Impressão como", "", "Edit1") Sleep(500) ; 粘贴文件名 ControlSetText("Salvar Saída de Impressão como", "", "Edit1", $sLastClip) Sleep(500) ; 点击保存按钮 ControlClick("Salvar Saída de Impressão como", "", "Button2") Sleep(500) ; 处理文件覆盖确认弹窗 WinWait("Confirmar Salvar como", "", 5) ControlClick("Confirmar Salvar como", "", "Button1")
关键注意事项
- 控件ID确认:使用AutoIT自带的Window Info工具,精准获取打印窗口内各控件的ID,避免因系统语言或Chrome版本不同导致识别失败。
- 键名兼容:部分新版Chrome可能将偏好键名改为
headerFooterEnabled,若原键名无效可尝试替换。 - kiosk模式调整:
--kiosk-printing会直接进入保存界面,若要通过UI修改设置,需移除该参数,先打开打印预览调整后再执行保存操作。
内容的提问来源于stack exchange,提问作者Filipe Vaz
相关产品推荐
相关产品推荐

