python - 使用 chromedriver 从 Selenium 打印 PDF

标签 python selenium selenium-chromedriver

我正在尝试使用 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()')

最佳答案

添加 --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']))

这里有一些您可以选择的选项 fiddle with

关于python - 使用 chromedriver 从 Selenium 打印 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59893671/

相关文章:

python - 当我在 PyQt4 中打开新窗口时如何关闭旧窗口

python - 将边界框外的 numpy 二维数组中的所有内容都设为零

python - 获取 DOM 树中元素的 XPath?

java - 如何将 Web 驱动程序实例传递给另一个类的方法

java - 如何使用java/python使用云栈API?

python - 等待条件变量超时 : lock not reacquired in time

java - 有没有办法在我的测试自动化套件目录中自动更新 chromedriver?

google-chrome - 禁用chrome下载多个文件确认

java - 尝试在 Jenkins 上运行 Selenium 时出现 NoSuchSession 异常

android - 在 Appium/Selendroid 中使用 "copy"和 "paste"