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

前端 未结 4 2007
忘了有多久
忘了有多久 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:05

    The solution is not very good, but you can take a screenshot and convert to pdf by Pillow...

    from selenium import webdriver
    from io import BytesIO
    from PIL import Image
    
    driver = webdriver.Chrome(executable_path='path to your driver')
    driver.get('your url here')
    img = Image.open(BytesIO(driver.find_element_by_tag_name('body').screenshot_as_png))
    img.save('filename.pdf', "PDF", quality=100)
    
    0 讨论(0)
  • 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': '<path>'
    }
    chrome_options.add_argument('--kiosk-printing')
    chrome_options.add_experimental_option('prefs', prefs)
    
    for dirpath, dirnames, filenames in os.walk('<source path>'):
        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()
    
    0 讨论(0)
  • 2021-02-04 17:21

    The answer here, worked when I did not have any other printer setup in my OS. But when I had another default printer, this did not work.

    I don't understand how, but making small change this way seems to work.

    from selenium import webdriver
    import json
    
    chrome_options = webdriver.ChromeOptions()
    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)}
    chrome_options.add_experimental_option('prefs', prefs)
    chrome_options.add_argument('--kiosk-printing')
    CHROMEDRIVER_PATH = '/usr/local/bin/chromedriver'
    driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=CHROMEDRIVER_PATH)
    driver.get("https://google.com")
    driver.execute_script('window.print();')
    driver.quit()
    
    0 讨论(0)
  • 2021-02-04 17:25

    Here is the solution I use with Windows :

    • First download the ChromeDriver here : http://chromedriver.chromium.org/downloads and install Selenium

    • Then run this code (based on the accepted answer, slightly modified to work on Windows):

      import json
      from selenium import webdriver
      chrome_options = webdriver.ChromeOptions()
      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)}
      chrome_options.add_experimental_option('prefs', prefs)
      chrome_options.add_argument('--kiosk-printing')
      browser = webdriver.Chrome(r"chromedriver.exe", options=chrome_options)
      browser.get("https://google.com/")
      browser.execute_script('window.print();')
      browser.close()    
      
    0 讨论(0)
提交回复
热议问题