无法在 Puppeteer .pdf 中的每个页面上重复/显示背景图像

问题描述 投票:0回答:1

我正在使用 Puppeteer 从 HTML 生成 PDF 页面。我遇到的问题是我无法令人满意地为 html->pdf 生成的每个页面创建覆盖整个页面的背景图像。

例如,在下面的代码中,如果 HTML 结果为 3 个 PDF 页面,则背景图像仅显示在第一页中。

如果我尝试将背景图像属性作为 body 的子级放入 div 标签中(位置:固定且宽度和高度为 100%),那么最后一页将只有页面的一部分,其中包含背景图像,而不是背景图像整页。

我正在 NodeJS 中执行此操作。

我希望看到每个生成的 PDF 页面中都出现背景图像。 然而下面的代码只显示第一页的背景图片。

请帮忙!



let args = [
    '--no-sandbox',
    '--disable-setuid-sandbox',
  ];


let options = {
      format: 'A5',
      printBackground: true,
      preferCSSPageSize: true
    };


const html = `
<html style="-webkit-print-color-adjust: exact; margin: 0;">
   <body style="background-image: url('https://...image.JPEG'), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5)); 
               background-position: fixed; 
               background-repeat: repeat; 
               background-size: 0 0/100% 100vh; 
               color: white; 
               margin: 0; 
               position: absolute; 
               top: 0; 
               z-index: 9999;">
      <div id="bodydiv" style="margin: 0;">
         <div id="contentwrapper" style="padding-bottom: 50px; padding-left: 50px; padding-right: 50px; padding-top: 50px;">
            <h1>hello <img src="https://...image.JPEG" style="border-radius: 15px; height: auto; width: 75%;"></h1>
         </div>
      </div>
   </body>
</html>
`;



  const browser = await puppeteer.launch({
    args: args
  });
  const page = await browser.newPage();
  await page.emulateMediaType('print');
  await page.setContent(html, {
        waitUntil: 'networkidle0', // wait for page to load completely
      });
  pdfObj['buffer'] = Buffer.from(Object.values(await page.pdf(options)));




puppeteer pdf-generation html-pdf
1个回答
0
投票

为了在每个页面上创建背景,我使用具有固定位置的块元素。 Puppeteer 在 pdf 的每一页上渲染这个固定元素。

为此“背景”元素设置以下 css 属性非常重要:

position: fixed;
top: 0;
left: 0;
right: 0;
height: 100vh;
z-index: -1;
background: ... ;

这是代码中的用法示例:

<html style="-webkit-print-color-adjust: exact; margin: 0">
  <body style="margin: 0">
    <style>
      .page-background {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: 100vh;
        z-index: -1;

        background-image: url('https://...image.JPEG'), linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5));
        background-position: fixed;
        background-repeat: repeat;
      }
    </style>
    <div class="page-background"></div>

    <div id="bodydiv" style="margin: 0">
      <div id="contentwrapper" style="padding-bottom: 50px; padding-left: 50px; padding-right: 50px; padding-top: 50px">
        <h1>hello <img src="https://...image.JPEG" style="border-radius: 15px; height: auto; width: 75%" /></h1>
      </div>
    </div>
  </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.