Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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.

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();')
like image 947
PKG Avatar asked Apr 04 '18 04:04

PKG


People also ask

How do I save a Print preview as a PDF in Chrome?

Go to File > Print. In the Destination Section, click the "Change..." Button. A "Select a destination" pop-up will appear. Click "Save as PDF" under the Local Destinations Section.


1 Answers

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

like image 167
PKG Avatar answered Oct 21 '22 13:10

PKG