Skip to content
Advertisement

How to change saved PDF page name with Selenium + Chromedrive

I have a script that uses Selenium Python to download a PDF page made based on this question

My goal at the moment is to change the name of this file so that it is located with the name I chose and then change the destination folder of the saved file.

My doubts are: Where should I change so that the file is saved with the name I choose?

Even with the changes made to the “prefs=” variable, the file continues to be saved in the default chrome directory.

At the moment I have the following code:

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless') # Escondendo o navegador
driver = webdriver.Chrome(options=chrome_options)
driver.maximize_window()
settings = {
    "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
        "isLandscapeEnabled": True,
        "selectedDestinationId": "Save as PDF",
        "version": 2,
    }

prefs = {
    "printing.print_preview_sticky_settings.appState": json.dumps(settings),
    "profile.default_content_settings.popups" : 0,

    "download.name":"name_file", # ?????? ESTE CÓDIGO NÃO ALTERA O NOME

    "download.default_directory": r'C:Usersdiretorio_escolhido\' # ESTE CÓDIGO NÃO ALTERA O DESTINO,

    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
}


chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(name_Object.url)
sleep(5) # Pausa para carregar os dados
driver.execute_script('window.print();')

print('Gerou o PDF')

Advertisement

Answer

Change download.default_directory to savefile.default_directory so your saving location works.

Sadly I think we can’t change the filename before download, but you can rename your file after download, by renaming the latest file in download folder:

import os    
import shutil
download_folder = "C:\Users\username\Downloads\Test"
filename = max([download_folder + "\" + f for f in os.listdir(Initial_path)],key=os.path.getctime)
shutil.move(filename,os.path.join(Initial_path,r"newPDFName.pdf"))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement