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

Weasyprint结合Bootstrap导出PDF时CSS背景色不生效问题求助

解决方案

1. 强制开启打印模式背景渲染

你当前调用WeasyPrint时指定了media_type='print',Bootstrap自带的打印样式会默认清空所有元素背景色,且打印模式默认禁用背景输出,添加以下全局CSS即可修复:

@media print {
  * {
    -webkit-print-color-adjust: exact;
    print-color-adjust: exact;
    color-adjust: exact;
  }
}

如果不需要严格遵循打印媒体样式规则,也可以直接将调用参数里的media_type='print'改为media_type='screen',直接用屏幕端样式渲染导出。

2. 修正自定义CSS语法并提升优先级

你现有的自定义样式存在选择器语法错误,且权重不足以覆盖Bootstrap默认规则,修改为以下内容:

.table-primary, 
.table-primary > td, 
.table-primary > th, 
.table-primary > tr {
  background-color: #459EAD !important;
}

添加!important强制覆盖Bootstrap自带样式,避免优先级不足导致规则不生效。

3. 调整样式加载顺序

自定义样式需要晚于Bootstrap样式加载才能生效,建议将自定义CSS同步传入stylesheets参数,放在Bootstrap CSS之后,参考修改后的调用代码:

weasyprint.HTML(
    string=self.html_accept(request, report, clinic_id), 
    media_type='print'
).write_pdf(stylesheets=[
    weasyprint.CSS(url='https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css'),
    weasyprint.CSS(string='''
    @media print {
      * {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
        color-adjust: exact;
      }
    }
    .table-primary, 
    .table-primary > td, 
    .table-primary > th, 
    .table-primary > tr {
      background-color: #459EAD !important;
    }
    ''')
])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 14:36:05