使用 chromedriver 从 Selenium 打印 PDF

2022-01-15 00:00:00 python selenium selenium-chromedriver

问题描述

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

I am trying to implement printing html/css contents as PDF with Selenium, chromedriver and python.

我可以使用以下代码进行打印,但无法更改打印设置.我想以 Letter 大小打印,没有页眉/页脚.官方信息 chromedriver 或 Selenium 并没有告诉我很多,所以我遇到了麻烦.有谁知道如何更改打印设置或永远无法完成.

I could printing with a below code, but I cannot change printing setting. I would like to print in Letter size and no header/footer. Official information chromedriver or Selenium doesn't tell me a lot, so I'm in trouble. Does anyone know that how printing setting can be changed or it can never be done.

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 并尝试如下:

Add --headless and try it like this:

pdf = driver.execute_cdp_cmd("Page.printToPDF", {
  "printBackground": True
})

import base64

with open("file.pdf", "wb") as f:
  f.write(base64.b64decode(pdf['data']))

这里有一些选项可以摆弄

相关文章