在无头模式下使用Selenium Chrome驱动程序打印PDF

umuewwlo  于 2022-12-06  发布在  Go
关注(0)|答案(1)|浏览(373)

我在没有headless模式的情况下打印没有问题,但是一旦我启用headless模式,它就拒绝打印PDF。我目前正在开发一个带有GUI的应用程序,所以如果可能的话,我宁愿终端用户看不到Selenium webdriver。
对于这个项目,我使用的是旧版本的Selenium 4.2.0,它与Python 3.9结合使用。

import os
from os.path import exists
import json
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver import Chrome, ChromeOptions

# Paths
dir_path = os.getcwd()
download_path = os.path.join(dir_path, "letters")
chrome_path = os.path.join(dir_path, "chromium\\app\\Chrome-bin\\chrome.exe")
user_data_path = os.path.join(dir_path, "sessions")

website = "https://www.google.com/"

def main():
    print_settings = {
        "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
        "selectedDestinationId": "Save as PDF",
        "version": 2,
        "isHeaderFooterEnabled": False,
        "isLandscapeEnabled": True
    }

    options = ChromeOptions()
    options.binary_location = chrome_path
    options.add_argument("--start-maximized")
    options.add_argument('--window-size=1920,1080')
    options.add_argument(f"user-data-dir={user_data_path}")
    options.add_argument("--headless")
    options.add_argument('--enable-print-browser')
    options.add_experimental_option("prefs", {
        "printing.print_preview_sticky_settings.appState": json.dumps(print_settings),
        "savefile.default_directory": download_path,  # Change default directory for downloads
        "download.default_directory": download_path,  # Change default directory for downloads
        "download.prompt_for_download": False,  # To auto download the file
        "download.directory_upgrade": True,
        "profile.default_content_setting_values.automatic_downloads": 1,
        "safebrowsing.enabled": True
    })
    options.add_argument("--kiosk-printing")

    driver = Chrome(service=Service(ChromeDriverManager().install()), options=options)
    driver.get(website)
    driver.execute_script("window.print();")

    if exists(os.path.join(user_data_path, "Google.pdf")):
        print("YAY!")
    else:
        print(":(")

if __name__ == '__main__':
    main()
q9rjltbz

q9rjltbz1#

对于遇到类似问题的其他人,我使用下面描述的print方法修复了它:Selenium print PDF in A4 format
使用上面的示例,我替换了:

driver.execute_script("window.print();")

与:

pdf_data = driver.execute_cdp_cmd("Page.printToPDF", print_settings)
with open('Google.pdf', 'wb') as file:
    file.write(base64.b64decode(pdf_data['data']))

这对我来说很有效。

相关问题