Home > Enterprise >  How to convert HTML to PDF using selenium 3.141.59?
How to convert HTML to PDF using selenium 3.141.59?

Time:09-24

I created an automation that goes into a website that has login and password, and when the automation finishes filling the form on the page, try to save in PDF

The problem is that in selenium 3, it doesn't have the same options as selenium 4 to save to PDF

Selenium 4 - I would use the code below to convert the HTML page to PDF in selenium 4

Map<String, Object> params = new HashMap();
String command = "Page.printToPDF";
Map<String, Object> output = chromeDriver.executeCdpCommand(command, params);

In selenium 3 if I put the same code it gives an error that the executeCdpCommand method does not exist.

I can't use selenium 4, due to company rules.

Does anyone have an alternative please?

CodePudding user response:

Simple python wrapper to convert HTML to PDF with headless Chrome via selenium.

Install

pip install pyhtml2pdf

Dependencies

-Selenium Chrome Webdriver [https://chromedriver.chromium.org/downloads] (If Chrome is installed on the machine you won't need to install the chrome driver) Ghostscript [https://www.ghostscript.com/download.html]

Example

Convert to PDF

Use with website url

from pyhtml2pdf import converter

converter.convert('https://pypi.org', 'sample.pdf') Use with html file from local machine

import os from pyhtml2pdf import converter

path = os.path.abspath('index.html') converter.convert(f'file:///{path}', 'sample.pdf') Some JS objects may have animations or take a some time to render. You can set a time out in order to help render those objects. You can set timeout in seconds

converter.convert(source, target, timeout=2) Compress the converted PDF

Some PDFs may be oversized. So there is a built in PDF compression feature.

The power of the compression,

0: default 1: prepress 2: printer 3: ebook 4: screen

converter.convert(source, target, compress=True, power=0) Compress PDF Use it to compress a PDF file from local machine

import os from pyhtml2pdf import compressor

compressor.compress('sample.pdf', 'compressed_sample.pdf') Inspired the works from,

https://github.com/maxvst/python-selenium-chrome-html-to-pdf-converter.git https://github.com/theeko74/pdfc

and you can find out more complete information by watching this https://www.youtube.com/watch?v=RHAZfjzxDtU&t=310s&ab_channel=CodingShiksha

  • Related