I am trying to print my html code to pdf by opening up the html document with selenium
(chrome-driver) in Python. Having opened the html file, I try to print the document to pdf but whenever I open the printer window (manually or through selenium
commands) it immediately shuts down.
I have tried with the following code which cannot produce a .pdf file:
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),
'savefile.default_directory': path_html}
chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')
browser = webdriver.Chrome(CHROMEDRIVER_PATH, options=chrome_options)
browser.get(path_html)
browser.execute_script('window.print();')
browser.close()
I am using the latest chromedriver version from https://chromedriver.chromium.org/downloads for windows.
If I simply open my own browser (not through selenium) I can easily print the html document to a .pdf file.
UPDATE:
If someone bumps into the sample problem, I solved the problem by utilizing the a wrapper that converts the html file to pdf - it essentially goes through the above code.
Check out: the converter
function from https://pypi.org/project/pyhtml2pdf/