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

使用Playwright生成PDF时background-color CSS属性不生效求助

Playwright生成PDF时background-color不生效的解决办法

Chromium引擎默认在生成PDF时不会渲染背景样式,这是浏览器打印的默认行为,和你用行内样式、JS设置无关,按以下步骤修改即可解决:

1. 开启PDF生成的背景打印参数

在调用page.pdf()方法时,必须添加print_background=True配置,这是让背景色生效的核心设置。

2. (可选)添加CSS强制渲染背景

在你的样式中加上-webkit-print-color-adjust: exact;属性,进一步确保背景色能被正确渲染,兼容更多场景。

修改后的完整代码示例

from playwright.sync_api import sync_playwright
from string import Template

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    
    footer_template = """
    <style>
        .footer {
            font-size: 10px;
            text-align: center;
            width: 100%;
            margin: 10px 1cm 0 1cm;
            font-family: "Times New Roman", sans-serif;
            background-color: red;
            -webkit-print-color-adjust: exact; /* 强制渲染背景 */
        }
        .footer-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: 100%;
            height: 100%;
        }
        .fw-bold {
            font-weight: bold;
        }
    </style>
    <div class="footer">
        <div class="footer-content">
            <p class="fw-bold">Powered By TECHstile.in</p>
            <p>This is a Computer Generated Invoice</p>
            <p>{{invoice_number}}-<strong><span class="pageNumber"></span>/<span class="totalPages"></span></strong></p>
        </div>
    </div>
    """
    template = Template(footer_template)
    # 渲染模板(替换成你的发票编号变量)
    rendered_footer = template.substitute(invoice_number="INV-001")
    
    # 主内容HTML示例
    html_content = """
    <html>
        <body>
            <h1>Invoice Details</h1>
            <p>Product: Example Item</p>
            <p>Amount: $100</p>
        </body>
    </html>
    """
    page.set_content(html_content, wait_until="networkidle")
    
    # 生成PDF,关键配置print_background=True
    page.pdf(
        path="invoice.pdf",
        print_background=True,
        footer_template=rendered_footer
    )
    browser.close()

注意点

  • 不管是页面内的样式还是footer_template里的样式,都需要依赖print_background=True才能让背景色生效。
  • 之前尝试的行内样式、JS设置无效,本质是因为浏览器默认关闭了打印背景的开关,必须通过Playwright的PDF生成参数手动开启。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 18:54:52