Skip to content

Instantly share code, notes, and snippets.

@kdrakon
Created May 15, 2023 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdrakon/12ec07f339c7d6e583b5b5809db9cafe to your computer and use it in GitHub Desktop.
Save kdrakon/12ec07f339c7d6e583b5b5809db9cafe to your computer and use it in GitHub Desktop.
Using Selenium and Chrome driver (with Dev tools) to download a page as a PDF
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
import base64
options = webdriver.ChromeOptions()
options.add_argument('--headless')
url = "https://google.com"
with webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=options) as driver:
driver.get(url)
pdf = driver.execute_cdp_cmd("Page.printToPDF", {
"printBackground": True,
"paperWidth": 8.5,
"paperHeight": 11,
})
with open("file.pdf", "wb") as f:
f.write(base64.b64decode(pdf['data']))
@kdrakon
Copy link
Author

kdrakon commented May 15, 2023

Needs pip install selenium webdriver-manager chromedriver-py

Documentation on Page.printToPDF here: https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment