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

时光毁灭记忆、已成空白 提交于 2020-12-30 06:53:06

问题


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.


回答1:


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();')



回答2:


I was able to find a possible solution.

The code saves an html file to pdf which is my ultimate goal.

The original post is:

Python + Selenium + PhantomJS render to PDF

Best.



来源:https://stackoverflow.com/questions/31136581/automate-print-save-web-page-as-pdf-in-chrome-python-2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!