使用Selify和ChromeDriver,可自动调整打印页面的大小

人气:873 发布:2022-10-16 标签: python printing selenium selenium-chromedriver chromium

问题描述

我正在编写一个脚本,以便在Chrome中自动打印一组网页。如果我要手动打印它们,我会从比例下拉菜单中选择"自定义",然后在下面的输入栏中输入50。

当我使用Selnium和ChromeDriver自动批量打印这些页面时,我想不出需要传入哪些参数来复制此设置。

appState = { "recentDestinations": [{
                "id": "Save as PDF",
                "origin": "local",
                "account": "",
                "printing.scaling": 'Custom', # <== Does it go here?
             }],
             "selectedDestinationId": "Save as PDF",
             "version": 2,
             "printing.scaling": 'Custom',  # <== Or here?
           }
profile = { 'printing.print_preview_sticky_settings.appState': json.dumps(appState),
            'printing.print_header_footer': False,

            # So many different versions of things I have tried :-(
            'printing.scaling': 'Custom',
            'printing.scaling_type': 'Custom',
            'print_preview.scaling': 'Custom',
            'print_preview.scaling_type': 'Custom',
            'printing.custom_scaling': True,
            'printing.fit_to_page_scaling': 50,
            'printing.page_scaling': True,
          }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)
br = webdriver.Chrome(options=chrome_options)

上面显示的所有不同选项都是在阅读了大量Chromium源代码以获取提示后猜测的。

https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc?view=markup https://chromium.googlesource.com/chromium/src/+/master/printing/print_job_constants.cc https://chromium.googlesource.com/chromium/src/+/master/printing/print_job_constants.h

我没有线索了……有谁有什么主意吗?谢谢!

推荐答案

经过多次搜索和反复试验,我终于找到了解决方案!该设置位于appState词典中,名为";scalingType";,但它是一个枚举,令人恼火的是,它似乎只接受定义为here (Github mirror)或here (googlesource)的数字。3提供自定义缩放,然后您可以在";scaling";设置(它是一个字符串!)中定义它。因此,我的设置现在如下所示:

chrome_options = webdriver.ChromeOptions()
appState = {"recentDestinations": [{"id": "Save as PDF", "origin": "local", "account": ""}],
            "selectedDestinationId": "Save as PDF",
            "version": 2,
            "isHeaderFooterEnabled": False,
            "isLandscapeEnabled": True,
            "scalingType": 3,
            "scaling": "141"}
prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(appState),
         'savefile.default_directory': BASE_DIR}
chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('kiosk-printing')

driver = webdriver.Chrome(f'{BASE_DIR}\chromedriver.exe', options=chrome_options)

当前伸缩类型选项为:

0:默认 1:适合页面 2:适合纸张 3:自定义

但我使用这两个"适合"选项都没有成功。

更一般地,这些设置/选项中的大多数可以通过查看铬源和/或其包含文件夹的this file来确定。

170