You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Selenium保存网页PDF时启用背景CSS选项

解决Selenium ChromeDriver打印PDF时背景图形不显示的问题

问题说明

手动勾选打印预览里的「Background graphics」选项时,报表头部渲染效果正常;但用Selenium脚本自动打印PDF时,没法启用这个选项,导致生成的PDF缺失背景内容。

解决办法

核心是在Chrome的打印偏好设置里正确配置背景图形参数,再配合页面CSS调整,确保背景被完整捕获。

1. 调整打印设置参数

在settings字典里启用cssBackground参数,根据Chromium的设置规则,将其值设为2即可对应勾选「Background graphics」选项。

2. 注入强制保留背景的CSS

通过JavaScript给页面添加打印专用的CSS样式,强制浏览器保留背景颜色和图形。

修改后的完整脚本

import selenium
from selenium import webdriver
import json
from time import sleep
import os

chrome_options = webdriver.ChromeOptions()
settings = {
    "recentDestinations": [{
            "id": "Save as PDF",
            "origin": "local",
            "account": "",
        }],
    "selectedDestinationId": "Save as PDF",
    "version": 2,
    "cssBackground": 2,  # 启用背景图形选项
    }

prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings), }
chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')
CHROMEDRIVER_PATH = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=CHROMEDRIVER_PATH)

driver.get("https://dash.gallery/dash-multipage-report/")
sleep(3)

# 注入CSS确保打印时保留背景
driver.execute_script("""
var style = document.createElement('style');
style.innerHTML = `
@media print {
  * {
    -webkit-print-color-adjust: exact !important;
    print-color-adjust: exact !important;
  }
}
`;
document.head.appendChild(style);
""")

driver.execute_script('window.print();')
sleep(5)
driver.quit()

补充说明

  • cssBackground: 2是Chromium内部对应启用背景图形的参数值,能直接设置打印预览的默认勾选状态。
  • 注入的CSS样式-webkit-print-color-adjust: exact会强制浏览器在打印时不忽略元素的背景样式,避免默认打印优化丢失背景内容。
  • --kiosk-printing参数让浏览器直接按设置打印,跳过手动确认弹窗,实现完全自动化。

内容的提问来源于stack exchange,提问作者khb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:45:57