Reputation: 221
So im generating multiple PDFs from URLS, then i use easy-pdf-merge to combine these PDFs,
I would like to be able to update the pageNumber and totalPages in every footer, so i would like to get the first PDFs totalPages and Page number and save that in a variable, then every PDF that gets created after will use the new variable i created + the previous pageNumber and totalPages. "Search Page number" and you will find the options. https://pptr.dev/#?product=Puppeteer&version=v1.19.0&show=api-class-page
Is this possible? I see in the pdf.options there are totalPages and pageNumber options.
const puppeteer = require('puppeteer');
class Webpage {
static async generatePDF(url) {
const browser = await puppeteer.launch({ headless: true }); // Puppeteer can only generate pdf in headless mode.
const page = await browser.newPage();
await page.goto(url); // Adjust network idle as required.
const pdfConfig = {
path: 'home.pdf', // Saves pdf to disk.
// format: 'A4',
printBackground: true,
margin: { // Word's default A4 margins
top: '2.54cm',
bottom: '2.54cm',
left: '2.54cm',
right: '2.54cm'
},
width: 1860,
height: 2631
};
await page.emulateMedia('screen');
const pdf = await page.pdf(pdfConfig); // Return the pdf buffer. Useful for saving the file not to disk.
await browser.close();
return pdf;
}
}
(async() => {
const url = ['https://google.com/'];
// doing some checks here to get more than 1 url
if(url > 1){
for(i=0;i<url.length;i++){
await Webpage.generatePDF(url[i]);
}
}
})();
i have done some digging, and found this question How does header and footer printing work in Puppeter's page.pdf API?
which helps a lot with understanding what is going on with puppeteer at the time, it seems to use Skia, which in turn uses chrome tools and this is where the page numbers come from in the end.
https://chromedevtools.github.io/devtools-protocol/tot/Page#method-printToPDF
but i still have no idea how i can save and use this variable for what i want to do.
Upvotes: 11
Views: 8355
Reputation: 1
You need to pass the footerTemplate while exporting the pdf. You can checkout this [Link].
await page.pdf({
format: 'A4',
displayHeaderFooter: true,
headerTemplate: ``,
footerTemplate: `
<div style="border-top: solid 1px #bbb; width: 100%; font-size: 9px;
padding: 5px 5px 0; color: #bbb; position: relative;">
<div style="position: absolute; left: 5px; top: 5px;"><span class="date"></span></div>
<div style="position: absolute; right: 5px; top: 5px;"><span class="pageNumber"></span>/<span class="totalPages"></span></div>
</div>
`,
// this is needed to prevent content from being placed over the footer
margin: { bottom: '70px' },
});
[1]: https://link
Upvotes: 0