Printing Webpage in a Specific Location in Selenium

Viewed 681

I have this code to go to Google and convert the page to a PDF.

# Program to go to Google and convert the page to a PDF
# But it saves in my downloads folder (I want it in a particular folder in the directory I ran this code)
from selenium import webdriver
import json

# Set up web driver
options = webdriver.ChromeOptions()
options.headless = False

options.add_argument("--kiosk-printing")

settings = {
    "recentDestinations": [{
        "id": "Save as PDF",
        "origin": "local",
        "account": "",
        'default_directory': 'folder' # This is the folder where i want to place my PDF (in the same directory as this
        # file) 
    }],
    "selectedDestinationId": "Save as PDF",
    "version": 2,

}

prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings)}
options.add_experimental_option('prefs', prefs)

driver = webdriver.Chrome(executable_path="chromedriver.exe", options=options)

driver.get("https://google.com")

# This gets saved in my downloads folder
driver.execute_script("window.print();")

But I want it to be saved in the folder called "folder", which is in the same directory as this Python file. 'default_directory': 'folder' did not work.

1 Answers
options = webdriver.ChromeOptions()
options.headless = False

options.add_argument("--kiosk-printing")
options.add_argument("--kiosk")

options.add_argument("--kiosk-printing")

settings = {
    "recentDestinations": [{
        "id": "Save as PDF",
        "origin": "local",
        "account": "",
    }],
    "selectedDestinationId": "Save as PDF",
    "version": 2,

}

prefs = {
    'printing.print_preview_sticky_settings.appState': json.dumps(settings), 
    "savefile.default_directory": r"C:\Users\prave\Downloads\travelBA\folder",
}
options.add_experimental_option('prefs', prefs)

driver = webdriver.Chrome(executable_path="chromedriver.exe", options=options)

driver.get("https://google.com")

# This gets saved in my downloads folder
driver.execute_script("window.print();")

input()

use saveFile.default_directory

Related