python - 使用 chromedriver 从 Selenium 打印 PDF
问题描述
我正在尝试使用 Selenium、chromedriver 和 python 将 html/css 内容打印为 PDF。
我可以使用以下代码进行打印,但无法更改打印设置。我想以 Letter 大小打印,没有页眉/页脚。官方资料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()')
解决方案
添加 --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']))
这里有一些你可以摆弄的选项
推荐阅读
- r - 用于格式化轴标签的空表达式
- python - 从 sklearn 运行投票分类器的正常时间是多少?
- vue.js - 如何显示插槽中组件的数据?
- r - R Highcharter:在 x 轴上,当数据框只有一个结果时,日期显示不正确
- arrays - VB.NET 如何将 Object(,) 转换为 String()
- excel - 如何根据单元格中的文本命名工作表?
- spring - 避免使用 If 语句来检查对象是否为 Null
- linux - 多线程对 IO 密集型任务没有帮助?
- wordpress - 在 wordpress 中归档文件
- xamarin.forms - 在 Xamarin Forms droid 上找不到错误资源