Created
May 15, 2023 04:42
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Needs
pip install selenium webdriver-manager chromedriver-py
Documentation on
Page.printToPDF
here: https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF