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

Selenium Chrome驱动打印PDF时MediaSize设置不生效问题求助

解决Chrome打印PDF始终为Legal尺寸的问题

问题核心

你配置了A2纸张的微米尺寸参数,但Chrome仍输出Legal尺寸,关键原因是**mediaSize配置缺少必填的name字段**,Chrome无法识别自定义尺寸规则,自动 fallback 到默认的Legal尺寸。

两种可行解决方案

方案1:使用Chrome内置标准A2纸张标识

直接指定Chrome内置的A2纸张名称,修改app_state中的mediaSize配置:

"mediaSize": {
    "name": "A2",
    "height_microns": 594000,
    "width_microns": 420000
}

方案2:自定义尺寸(兼容不同地区Chrome版本)

如果标准A2标识不生效,用自定义尺寸规则强制Chrome使用指定参数:

"mediaSize": {
    "name": "CUSTOM",
    "height_microns": 594000,
    "width_microns": 420000,
    "custom_display_name": "A2"
}

完整修改后的代码

import json
from selenium import webdriver
import time

url = 'file:///C:/Users/XYZ/Downloads/page_1.html'

# 配置打印状态
app_state = {
    "recentDestinations": [
        {
            "id": "Save as PDF",
            "origin": "local",
            "account": ""
        }
    ],
    "selectedDestinationId": "Save as PDF",
    "isCssBackgroundEnabled": True,
    "isHeaderFooterEnabled": False,
    "isLandscapeEnabled": False,
    "version": 2,
    # 替换为方案1或方案2的mediaSize配置
    "mediaSize": {
        "name": "A2",
        "height_microns": 594000,
        "width_microns": 420000
    }
}

profile = {
    'printing.print_preview_sticky_settings.appState': json.dumps(app_state),
    # 确保默认选中"Save as PDF"
    'printing.default_destination_selection_rules': {
        "kind": "local",
        "namePattern": "Save as PDF"
    },
    'printing.print_to_file': True
}

chrome_options = webdriver.ChromeOptions() 
chrome_options.add_experimental_option('prefs', profile) 
chrome_options.add_argument('--kiosk-printing')

driver = webdriver.Chrome(options=chrome_options) 
driver.get(url)
time.sleep(3)  # 延长等待时间确保页面完全加载
driver.execute_script('window.print();')
driver.quit()

额外排查建议

  1. 暂时移除--kiosk-printing参数,手动打开打印预览,确认纸张尺寸是否正确显示,排查是配置不生效还是自动打印环节的问题。
  2. 检查Chrome全局打印设置,确保没有全局默认纸张尺寸覆盖Selenium的配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 01:52:44