Home > Software design >  How to change saved PDF page name with Selenium Chromedrive
How to change saved PDF page name with Selenium Chromedrive

Time:04-18

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:\Users\diretorio_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')

CodePudding user response:

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"))
  • Related