简体   繁体   English

在 chrome 中自动打印/保存网页为 pdf - python 3.6

[英]Automate print/save web page as pdf in chrome - python 3.6

I am trying to create a script to automatically save read-only pdfs via Chrome's printing functionality to save it as another pdf in the same folder.我正在尝试创建一个脚本,通过 Chrome 的打印功能自动保存只读 pdf,以将其另存为同一文件夹中的另一个 pdf。 This removes the 'read-only' feature.这将删除“只读”功能。 However while running the script I am not sure where I can specify my own specific destination folder and the script saves it in the Downloads folder directly.但是,在运行脚本时,我不确定在哪里可以指定我自己的特定目标文件夹,脚本将其直接保存在下载文件夹中。

Full props to https://stackoverflow.com/users/1432614/ross-smith-ii for the code below.以下代码的完整道具https://stackoverflow.com/users/1432614/ross-smith-ii

Any help will be very much appreciated.任何帮助将不胜感激。

import json
from selenium import webdriver
downloadPath = r'mypath\downloadPdf\\'
appState = {
"recentDestinations": [
    {
        "id": "Save as PDF",
        "origin": "local"
    }
],
"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) 
pdfPath = r'mypath\protected.pdf' 
driver.get(pdfPath) 
driver.execute_script('window.print();')

Ok, I think I figured out the solution.好的,我想我找到了解决方案。 Just append the following line with the below code:只需添加以下代码行:

profile = {'printing.print_preview_sticky_settings.appState':json.dumps(appState),'savefile.default_directory':downloadPath}

It's not ideal still as you cannot specify the new file name you want but it works for now.它仍然不理想,因为您无法指定所需的新文件名,但现在可以使用。

If anyone has a better solution, please do post it here.如果有人有更好的解决方案,请在此处发布。 Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM