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

Puppeteer生成PDF时background-color属性失效的解决办法

解决Puppeteer生成PDF时background-color不生效的问题

问题核心是Chrome(Puppeteer基于Chrome/Chromium)默认在打印模式下会禁用背景样式渲染,目的是节省打印墨水,所以Puppeteer的page.pdf()方法默认继承了这个行为,导致你的背景色被忽略。

解决方案

在调用page.pdf()时添加printBackground: true选项,强制启用背景渲染:

const puppeteer = require('puppeteer');

async function generatePDF() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  
  const htmlContent = `
    <html>
      <head>
        <title>PDF Report</title>
      </head>
      <body>
        <div style="background-color: red; padding: 20px;">
          <h1>Sample Report</h1>
          <p>This is a sample PDF report with a red background.</p>
        </div>
      </body>
    </html>
  `;
  
  await page.setContent(htmlContent);
  // 添加printBackground: true选项
  const pdfBuffer = await page.pdf({ 
    format: 'A4',
    printBackground: true 
  });
  
  await browser.close();
  
  return pdfBuffer;
}

generatePDF().then(pdfBuffer => {
  // Handle PDF buffer
});

补充说明

  • 这个选项会强制Chromium渲染HTML中的背景色、背景图片等所有背景相关样式,和你在浏览器中手动开启"打印背景图形"选项的效果一致。
  • 你的其他样式(如padding)正常生效,是因为这类盒模型样式不属于背景渲染范畴,不受打印模式的默认限制。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 19:27:34