问题
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.
回答1:
There is no "out of box" puppeteer implementation of the feature you are requesting.
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.
来源:https://stackoverflow.com/questions/52404672/puppeteer-custom-header-footer-for-pdf-render