/
html_to_pdf_converter.py
36 lines (31 loc) · 1.19 KB
/
html_to_pdf_converter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import json, base64
def send_devtools(driver, cmd, params={}):
resource = "/session/%s/chromium/send_command_and_get_result" % driver.session_id
url = driver.command_executor._url + resource
body = json.dumps({'cmd': cmd, 'params': params})
response = driver.command_executor._request('POST', url, body)
if response.get('status'):
raise Exception(response.get('value'))
return response.get('value')
def get_pdf_from_html(path, chromedriver='./chromedriver', print_options = {}):
webdriver_options = Options()
webdriver_options.add_argument('--headless')
webdriver_options.add_argument('--disable-gpu')
driver = webdriver.Chrome(chromedriver, options=webdriver_options)
driver.get(path)
calculated_print_options = {
'landscape': False,
'displayHeaderFooter': False,
'printBackground': True,
'preferCSSPageSize': True,
}
calculated_print_options.update(print_options)
result = send_devtools(driver, "Page.printToPDF", calculated_print_options)
driver.quit()
return base64.b64decode(result['data'])
if __name__ == "__main__":
pass
# TODO: add short help layout