Home > Blockchain >  Printing a PDF with Selenium Chrome Driver in headless mode
Printing a PDF with Selenium Chrome Driver in headless mode

Time:09-14

I have no problems printing without headless mode, however once I enable headless mode, it just refuses to print a PDF. I'm currently working on an app with a GUI, so I'd rather not have the Selenium webdriver visible to the end user if possible.

For this project I'm using an older version of Selenium, 4.2.0. That coupled with 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()

CodePudding user response:

For anyone else coming across this with a similar issue, I fixed it by using the print method described here: Selenium print PDF in A4 format

Using my example from above, I replaced:

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

with:

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

And that worked just fine for me.

  • Related