how to save opened page as pdf in Selenium (Python)

前端 未结 4 2006
忘了有多久
忘了有多久 2021-02-04 16:20

Have tried all the solutions I could find on the Internet to be able to print a page that is open in Selenium in Python. However, while the print pop-up shows up, after a second

4条回答
  •  [愿得一人]
    2021-02-04 17:10

    You can use the following code to print PDFs in A5 size with background css enabled:

    import os
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    import json
    import time
    
    chrome_options = webdriver.ChromeOptions()
    
    settings = {
        "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": ""
        }],
        "selectedDestinationId": "Save as PDF",
        "version": 2,
        "isHeaderFooterEnabled": False,
        "mediaSize": {
            "height_microns": 210000,
            "name": "ISO_A5",
            "width_microns": 148000,
            "custom_display_name": "A5"
        },
        "customMargins": {},
        "marginsType": 2,
        "scaling": 175,
        "scalingType": 3,
        "scalingTypePdf": 3,
        "isCssBackgroundEnabled": True
    }
    
    mobile_emulation = { "deviceName": "Nexus 5" }
    chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
    chrome_options.add_argument('--enable-print-browser')
    #chrome_options.add_argument('--headless')
    
    prefs = {
        'printing.print_preview_sticky_settings.appState': json.dumps(settings),
        'savefile.default_directory': ''
    }
    chrome_options.add_argument('--kiosk-printing')
    chrome_options.add_experimental_option('prefs', prefs)
    
    for dirpath, dirnames, filenames in os.walk(''):
        for fileName in filenames:
            print(fileName)
            driver = webdriver.Chrome("./chromedriver", options=chrome_options)
            driver.get(f'file://{os.path.join(dirpath, fileName)}')
            time.sleep(7)
            driver.execute_script('window.print();')
            driver.close()
    

提交回复
热议问题