Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automate print/save web page as pdf in chrome - python 2.7

I am trying to automate Print Save Web Page as pdf in chrome.

I have checked the webbrowser module, but it does not seem to be intended for this purpose.

I explored wkhtmltopdf as an alternative but when downloading the file it seems to be infected by a virus.

Thank you for the suggestions.

like image 380
Diego Avatar asked Jun 30 '15 11:06

Diego


People also ask

How do I print an entire Web page in Chrome?

Open the web page. 2. Press Ctrl + A 3. Right click on the page and left click on “Print” 4.


1 Answers

This worked for me using Chrome 62.0.3202.94, ChromeDriver 2.33.506120, Selenium 3.4.3, and Python 2.7.14 or 3.6.3, on Windows 7 x64:

import json
from selenium import webdriver

appState = {
    "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local",
            "account": ""
        }
    ],
    "selectedDestinationId": "Save as PDF",
    "version": 2
}

profile = {'printing.print_preview_sticky_settings.appState': json.dumps(appState)}

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option('prefs', profile)
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get('https://www.google.com/')
driver.execute_script('window.print();')
like image 105
Ross Smith II Avatar answered Oct 11 '22 11:10

Ross Smith II