使用chromedriver从Selenium打印PDF

2024-09-30 14:23:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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()')

Tags: importjsonpdfoshtmldriversettingchromedriver
1条回答
网友
1楼 · 发布于 2024-09-30 14:23:15

添加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

相关问题 更多 >