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

Python Selenium调用Chrome打印A4 PDF分页内容截断问题求解

Selenium Chrome 批量打印PDF分页截断问题修复方案

1. 补全打印配置参数

原有配置未明确锁定A4纸张参数、打印边距,会导致浏览器使用默认配置出现内容偏移截断,直接替换原有settings配置即可:

import json
from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
settings = {
    "recentDestinations": [{
        "id": "Save as PDF",
        "origin": "local",
        "account": "",
    }],
    "selectedDestinationId": "Save as PDF",
    "version": 2,
    "isHeaderFooterEnabled": False,
    # 明确指定A4纸张尺寸(单位:微米)
    "mediaSize": {
        "height_microns": 297000,
        "width_microns": 210000
    },
    # 边距设置:0=自定义 1=默认 2=最小边距
    "marginsType": 0,
    "customMargins": {
        "marginTop": 15,
        "marginBottom": 15,
        "marginLeft": 10,
        "marginRight": 10
    },
    "isCssBackgroundEnabled": True # 按需开启,需要打印背景色/图片时保留
}
prefs = {'printing.print_preview_sticky_settings.appState': json.dumps(settings)}
chrome_options.add_experimental_option('prefs', prefs)
chrome_options.add_argument('--kiosk-printing')
# 新版Selenium需将chrome_options参数改为options
browser = webdriver.Chrome(options=chrome_options)

2. 注入分页保护CSS

浏览器默认分页逻辑不会考虑内容完整性,需要在执行打印前注入CSS规则,强制避免元素内部分页、孤行截断:

# 访问目标页面后,打印前执行以下代码
browser.execute_script("""
const printStyle = document.createElement('style');
printStyle.textContent = `
@page {
    size: A4;
    margin: 15mm 10mm;
}
* {
    page-break-inside: avoid !important;
    break-inside: avoid !important;
}
p, li, .content-block {
    orphans: 3 !important;
    widows: 3 !important;
}
body {
    padding: 0 !important;
    margin: 0 !important;
    width: 210mm !important;
}
`;
document.head.appendChild(printStyle);
""")

# 等待CSS生效后触发打印
import time
time.sleep(0.5)
browser.execute_script('window.print();')

可选优化

如果页面内容宽度适配异常,可以在启动浏览器时指定视口尺寸匹配A4比例:
chrome_options.add_argument('--window-size=794,1123')
(794x1123是A4纸张对应96DPI下的像素尺寸,可根据实际页面调整)


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:39:02