用于PDF渲染的Puppeteer自定义页眉页脚

时间:2018-09-19 11:19:20

标签: pdf-generation puppeteer google-chrome-headless

我正在渲染网站的PDF。我想要第一页的页眉和页脚不同,其余页面的页眉和页脚不同。有什么办法吗?

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');
})();

如何实现?请帮忙。

1 个答案:

答案 0 :(得分:1)

您所请求的功能没有“即开即用”的伪造者实现。

同时,在“ Ability to prevent header/footer on certain pages”中描述了几种变通方法。第一个建议是使用不同的范围和使用不同的页眉/页脚组合多次转换。在将生成的缓冲区与https://github.com/astefanutti/decktape之类的东西合并之后。另一个使用@page:first CSS样式的骇人解决方案。