首页 > 解决方案 > 使用 chromedriver 从 Selenium 打印 PDF

问题描述

我正在尝试使用 Selenium、chromedriver 和 python 将 html/css 内容打印为 PDF。

我可以使用以下代码进行打印,但无法更改打印设置。我想以 Letter 大小打印,没有页眉/页脚。官方资料chromedriverSelenium并没有告诉我很多,所以我有麻烦了。有谁知道如何更改打印设置或永远无法完成。

import json
import os
from selenium import webdriver

# setting html path
htmlPath = os.getcwd() + "\\sample.html"
addr = "file:///" + htmlPath

# setting Chrome Driver
chromeOpt = webdriver.ChromeOptions()
appState = {
   "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local",
            "account": ""
        }
    ],
    "selectedDestinationId": "Save as PDF",
    "version": 2
}
prefs = {
    'printing.print_preview_sticky_settings.appState': json.dumps(appState)}
chromeOpt.add_experimental_option('prefs', prefs)
chromeOpt.add_argument('--kiosk-printing')
driver = webdriver.Chrome('.\\bin\\chromedriver', options=chromeOpt)

# HTML open and print
driver.get(addr)
driver.execute_script('return window.print()')

标签: pythonseleniumselenium-chromedriver

解决方案


添加 --headless 并像这样尝试:

pdf = driver.execute_cdp_cmd("Page.printToPDF", {
  "printBackground": True
})

import base64

with open("file.pdf", "wb") as f:
  f.write(base64.b64decode(pdf['data']))

这里有一些你可以摆弄的选项


推荐阅读