本文介绍了用于 PDF 渲染的 Puppeteer 自定义页眉页脚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在渲染网站的 PDF.我希望第一页的页眉和页脚不同,其余页面的页眉和页脚也不同.有没有办法做到这一点?

I am working on rendering a PDF of a site. I want different headers and footers for the first page and different for the rest of the pages. Is there any way to do this?

const puppeteer = require('puppeteer');

(async() => {
 var t = Date.now();
 console.log('Current time ' + t + ' msec'); 

 const browser = await puppeteer.launch({executablePath: 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe', ignoreHTTPSErrors:true, headless:true, devtools:false});
const page = await browser.newPage();
await page.setViewport({width: 1920, height: 1080});

await page.setExtraHTTPHeaders({'Report-Print-Preview-Mode':'true'});
await page.goto('https://localhost', {waitUntil: 'networkidle2'});
await page.type('#username', 'scott');
await page.type('#password', 'tiger');  
await page.click('[id="login_button"]');

await page.waitForSelector('[id="new_page_table_id"]');
await page.on('console', msg => console.log('PAGE LOG:', msg.text()));

// page.pdf() is currently supported only in headless mode.
// @see https://bugs.chromium.org/p/chromium/issues/detail?id=753118

await page.pdf({
path: 'report.pdf',
displayHeaderFooter: true,
headerTemplate: '<span style="font-size: 30px; width: 50px; height: 50px; background-color: black; color:black; margin: 20px;">Header</span>', 
footerTemplate: '<span style="font-size: 30px; width: 50px; height: 50px; background-color: black; color:black; margin: 20px;">Footer</span>',
printBackground: true,
format: 'A4',
margin:{top:'2cm',right:'2cm',bottom:'2cm',left:'2cm'}
});

await browser.close();

t = Date.now() - t;
console.log('Execution time ' + t + ' msec');
})();

我怎样才能实现它?请帮忙.

How can I achieve it? Please help.

推荐答案

您请求的功能没有开箱即用"的 puppeteer 实现.

There is no "out of box" puppeteer implementation of the feature you are requesting.

同时,能够防止某些页面上的页眉/页脚".第一个建议是使用不同的范围和使用不同的页眉/页脚组合进行多次转换;将结果缓冲区与 https://github.com/astefanutti/decktape 之类的内容合并后.另一个使用 @page:first CSS 样式的hacky 解决方案.

In the same time there are a couple of ways as work around described at "Ability to prevent header/footer on certain pages". The first suggestion is to convert multiple times with different range and use of different header/footer combos; after merge resulting buffers with something like https://github.com/astefanutti/decktape. And another, hacky solution by using @page:first CSS style.

这篇关于用于 PDF 渲染的 Puppeteer 自定义页眉页脚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 00:24