Skip to content

Instantly share code, notes, and snippets.

@404Wolf
Last active June 26, 2023 17:56
Show Gist options
  • Save 404Wolf/634e3e932a92d81a536c6e3bad7537ba to your computer and use it in GitHub Desktop.
Save 404Wolf/634e3e932a92d81a536c6e3bad7537ba to your computer and use it in GitHub Desktop.
Render a chrome-viewable file to a PDF with python
import atexit
import base64
import os
from time import sleep
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
service = Service(ChromeDriverManager().install())
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--kiosk-printing")
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-extensions")
webdriver_chrome = webdriver.Chrome(service=service, options=chrome_options)
atexit.register(webdriver_chrome.close)
from src.converter.engine import webdriver_chrome
def render(data: str, mimetype: str, width: int, height: int) -> str:
"""
Convert a chrome preview-able file to a base-64 encoded pdf using Selenium.
Args:
data (str): Base64 encoded preview-able file.
mimetype (str): The mimetype of the base64 data.
width (float): The width of the preview-able file.
height (float): The height of the preview-able file.
Returns:
str: The base64 encoded pdf.
"""
assert isinstance(width, (float, int)), f"Width must be num, not {type(width)}."
assert isinstance(height, (float, int)), f"Height must be num, not {type(height)}."
# Load in a blank HTML page
webdriver_chrome.get(f"about:blank")
# Execute a chrome-devtools-protocol command to change the window size
webdriver_chrome.execute_cdp_cmd(
"Emulation.setVisibleSize",
{
"width": width,
"height": height,
},
)
# Ship js to the console in our browser
webdriver_chrome.execute_script(
"document.body.style.margin = '0';"
"const content = document.createElement('img');"
f"content.src = 'data:{mimetype};base64,{data}';"
"content.style.width = '100%';"
"content.style.height = '100%';"
"document.body.appendChild(content);"
)
# Print to PDF with output as base64
pdf = webdriver_chrome.execute_cdp_cmd(
"Page.printToPDF",
{
"printBackground": False,
"landscape": False,
"displayHeaderFooter": False,
"scale": 1.5,
"paperWidth": 1.75,
"paperHeight": 2.5,
"marginTop": 0,
"marginBottom": 0,
"marginLeft": 0,
"marginRight": 0,
},
return pdf["data"] # The base64 encoded PDF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment