0

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/

Spedtsberg
  • 45
  • 1
  • 7
  • Since you have retrieved the html with Selenium you could always convert it to pdf with other modules like [weasyprint](https://pypi.org/project/weasyprint/) – RJ Adriaansen Jul 25 '22 at 07:55
  • Is the weasyprint framework better suited for converting html to pdf than wkhtmltopdf? I've spent many hours with wkhmltopdf which in the end was not suited for the task since it cannot handle image grids. – Spedtsberg Jul 25 '22 at 08:03
  • Does this answer your question? [how to save opened page as pdf in Selenium (Python)](https://stackoverflow.com/questions/56897041/how-to-save-opened-page-as-pdf-in-selenium-python) – Barry the Platipus Jul 25 '22 at 09:42
  • Please see my update above. Removing all other printers enables me to save as PDF. However, the script stops at the pop-up window where I have to name the file. How can I skip this last part such that it simply download the file with perhaps some prespecified file name? – Spedtsberg Jul 25 '22 at 10:50
  • I see that you solved this issue already. Here is one of my old answers that shows how to do this with `selenium` -- https://stackoverflow.com/questions/68164550/selenium-print-pdf-in-a4-format/68353518#68353518 – Life is complex Jul 26 '22 at 12:29

0 Answers0