Last modified: Dec 02, 2023 By Alexander Williams
Python Selenium: Print Page to PDF - Examples
Table Of Contents
Example 1: Print Page to PDF Using Chrome Options
from selenium import webdriver
# Create a ChromeOptions instance
chrome_options = webdriver.ChromeOptions()
# Set the 'print-to-pdf' flag in the ChromeOptions
chrome_options.add_argument('--kiosk-printing')
# Create a Chrome driver with the configured ChromeOptions
driver = webdriver.Chrome(options=chrome_options)
# Navigate to a webpage
driver.get('https://example.com')
# Print the page to PDF
driver.execute_cdp_cmd('Page.printToPDF', {'landscape': True, 'printBackground': True})
# Save the PDF to a file
with open('output.pdf', 'wb') as file:
file.write(driver.execute_cdp_cmd('Page.printToPDF', {'landscape': True, 'printBackground': True})['data'])
# Close the browser
driver.quit()
Output:
# The webpage is printed to a PDF file named 'output.pdf'
Example 2: Print Page to PDF with Custom Page Size
from selenium import webdriver
# Create a ChromeOptions instance
chrome_options = webdriver.ChromeOptions()
# Set the 'print-to-pdf' flag in the ChromeOptions
chrome_options.add_argument('--kiosk-printing')
# Create a Chrome driver with the configured ChromeOptions
driver = webdriver.Chrome(options=chrome_options)
# Navigate to a webpage
driver.get('https://example.com')
# Set custom page size (width x height) in millimeters
page_size = {'width': 210, 'height': 297}
# Print the page to PDF with custom page size
pdf_options = {'paperWidth': page_size['width'], 'paperHeight': page_size['height'], 'printBackground': True}
pdf_content = driver.execute_cdp_cmd('Page.printToPDF', pdf_options)['data']
# Save the PDF to a file
with open('output_custom_size.pdf', 'wb') as file:
file.write(pdf_content)
# Close the browser
driver.quit()
Output:
# The webpage is printed to a PDF file with custom page size named 'output_custom_size.pdf'