Skip to content
Advertisement

How to specify print location for PDF printing with Selenium

Whatever I do, the files keep getting printed into my Downloads (Windows default) folder, rather than specified folder. I did my research and apparently the savefile.default_directory option should be used rather than download.default_directory but it doesn’t work anyway. I tried removing the trailing \ from the path with no success. This is on a work PC if it makes any difference, Windows 10 machine.

   import os
   os.environ["PATH"] += os.pathsep + r'C:Program Files (x86)Chromedriver99';

   from selenium.webdriver.chrome.options import Options
   from selenium import webdriver

   options = Options()
    options.add_experimental_option(
        "prefs",
        {
            "download.prompt_for_download": False,
            "profile.default_content_setting_values.automatic_downloads": 1,
            "download.default_directory": r"C:UsersLucasDownloadsECV\",
            "savefile.default_directory": r"C:UsersLucasDownloadsECV\",
            "download.directory_upgrade": True,
            "safebrowsing.enabled": True # Some answers include this, makes no difference
        },
    )
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)

    # PDF printing settings
    print_settings = {
       "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
        "selectedDestinationId": "Save as PDF",
        "version": 2,
        "isHeaderFooterEnabled": False,
        "isLandscapeEnabled": True
    }

    prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(print_settings)}
    options.add_experimental_option('prefs', prefs)
    options.add_argument('--kiosk-printing') # Some answers include this, makes no difference


    driver = webdriver.Chrome(options=options)
    driver.get('https://stackoverflow.com/')
    driver.execute_script('window.print();')

Advertisement

Answer

You have two issues, the first one is that you are setting prefs twice, and since add_experimental_option() is using a dictionary for the options the second setting overrides the first one, and all those settings are actually deleted.

self._experimental_options = {}


def add_experimental_option(self, name, value):
    """
    Adds an experimental option which is passed to chrome.

    Args:
      name: The experimental option name.
      value: The option value.
    """
    self._experimental_options[name] = value

The second issue is the use of raw string r on the path, it evaluates to C:UsersLucasDownloadsECV\\ which is invalid. Either use / rather than "C:/Users/Lucas/Downloads/ECV/" or use \ without r "C:\Users\Lucas\Downloads\ECV\"

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

prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(print_settings),
         "download.prompt_for_download": False,
         "profile.default_content_setting_values.automatic_downloads": 1,
         "download.default_directory": "C:\Users\Lucas\Downloads\ECV\",
         "savefile.default_directory": "C:\Users\Lucas\Downloads\ECV\",
         "download.directory_upgrade": True,
         "safebrowsing.enabled": True}

options = Options()
options.add_experimental_option('prefs', prefs)
options.add_argument('--kiosk-printing')

driver = webdriver.Chrome(options=options)
driver.get('https://stackoverflow.com/')
driver.execute_script('window.print();')
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement