Python 使用chromedriver从Selenium打印PDF

Python 使用chromedriver从Selenium打印PDF,python,selenium,selenium-chromedriver,Python,Selenium,Selenium Chromedriver,我正在尝试使用Selenium、chromedriver和python实现将html/css内容打印为PDF 我可以用下面的代码打印,但无法更改打印设置。我想打印字母大小,没有页眉/页脚。官方信息或没有告诉我很多,所以我有麻烦了。是否有人知道如何更改打印设置,或者永远无法更改打印设置 import json import os from selenium import webdriver # setting html path htmlPath = os.getcwd() + "\\sampl

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

我可以用下面的代码打印,但无法更改打印设置。我想打印字母大小,没有页眉/页脚。官方信息或没有告诉我很多,所以我有麻烦了。是否有人知道如何更改打印设置,或者永远无法更改打印设置

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()')
添加--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']))
以下是一些选项,您可以添加--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']))

以下是一些选项,您可以

Chromedriver 2.39不起作用,但在我更新到最新版本(我的环境为79.0.3945.36)后,它确实起作用。非常感谢。Chromedriver 2.39不起作用,但在我更新到最新版本(我的环境是79.0.3945.36)后,它确实起作用了。非常感谢你。