[Python] How do you save a PDF from Selenium Driver in python?

Discussão em 'Python' iniciado por Stack, Setembro 14, 2025.

  1. Stack

    Stack Membro Participativo

    python - 3.9.15

    selenium - 4.7.0

    firefox - 108.0.1 (64-bit)

    I'm developing a script that captures a static image of an online dashboard using selenium. I've tried...

    driver.save_screenshot()


    However, the image is too low in quality to share with our constituents. When I manually 'Save to PDF' and adjust the scale, paper size, and margin, I'm able to print out a functional and high resolution pdf.

    I'm able to launch a print window with the following method and a print dialog box pops up. See image below.

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


    see image

    However, I am unable to interact with the dialog box because the python console hangs on the execute_script method. I know how to send_keys to adjust the settings, but I cannot use these functions because I can't interact with the python console when the print dialog box is popped up.

    Given the block below, I'm wondering if there are additional preferences available to set default print settings such as 'landscape', 50% scale, 1 inch margins, etc. There are other settings to automatically 'Save to PDF' I believe. However, these settings alone will not adjust the orientation, scale, etc.

    fp = webdriver.FirefoxProfile()
    fp.set_preference("browser.download.folderList", 2)
    fp.set_preference("browser.download.manager.showWhenStarting", False)
    fp.set_preference("browser.download.dir", os.getcwd())
    fp.set_preference("browser.helperApps.neverAsk.saveToDisk", mime_types)
    fp.set_preference("plugin.disable_full_page_plugin_for_types", mime_types)
    fp.set_preference("pdfjs.disabled", True)
    fp.set_preference("dom.disable_beforeunload", True)

    Continue reading...

Compartilhe esta Página