Selenium设置PDF打印偏好被Microsoft Print to PDF覆盖问题求助
解决方案
调整Chrome打印偏好配置
你的问题核心是Chrome的打印粘性设置未完全覆盖系统默认的Microsoft Print to PDF选项,需要补充关键参数强制指定默认打印目标为Chrome内置的"Save as PDF":
url = 'google.com' # 实际登录页URL与此不同 webdriver_service = Service('C:/Users/liamw/Downloads/chromedriver_win32/chromedriver.exe') chrome_options = Options() chrome_options.add_experimental_option('prefs', { # 强制设置打印预览的默认目标为Chrome内置Save as PDF 'printing.print_preview_sticky_settings.appState': { 'recentDestinations': [{ 'id': 'Save as PDF', 'origin': 'local', 'account': '', 'targetName': 'Save as PDF' # 新增参数明确目标名称 }], 'selectedDestinationId': 'Save as PDF', 'version': 2 }, # 添加默认目标选择规则,优先匹配Chrome内置PDF选项 'printing.default_destination_selection_rules': { 'kind': 'local', 'namePattern': 'Save as PDF' }, 'savefile.default_directory': 'C:/Users/liamw/Downloads/CAM Download Directory', # 避免系统打印对话框冲突 'printing.disable_print_to_file': False }) chrome_options.add_argument('--kiosk-printing') # 可选:禁用Chrome内置PDF查看器,直接触发下载(若目标页为PDF) chrome_options.add_argument('--disable-pdf-viewer') driver = webdriver.Chrome(service=webdriver_service, options=chrome_options) driver.get(url) # ... 登录或其他前置操作 driver.execute_script("window.print();")
额外排查步骤
- 版本匹配:确保ChromeDriver版本与本地Chrome浏览器版本完全一致,版本不兼容会导致偏好设置失效。
- 清理缓存:关闭所有Chrome实例,清理浏览器缓存后重新运行脚本,避免旧打印设置残留。
- 临时排查系统打印机:若上述配置仍无效,可临时禁用Microsoft Print to PDF打印机,测试是否为系统优先级导致的覆盖。
内容的提问来源于stack exchange,提问作者Liam Warin
相关产品推荐
相关产品推荐

