我正在尝试使用Selenium,chromedriver和python将html/css内容打印为PDF。
我可以使用以下代码打印,但我无法更改打印设置。我想以字母大小打印,没有页眉/页脚。官方信息chromedriver或Selenium并没有告诉我很多,所以我遇到了麻烦。有谁知道打印设置可以更改或永远无法完成。
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()')
添加 --无头并尝试如下:
pdf = driver.execute_cdp_cmd("Page.printToPDF", {
"printBackground": True
})
import base64
with open("file.pdf", "wb") as f:
f.write(base64.b64decode(pdf['data']))
以下是您可以摆弄的一些选项