Blog
Print header, footer, page numbers on PDF with Headless Chrome
Intro
Surprisingly, if you are using Headless Chrome to generate PDFs, you may find that getting header html, footer html, and page numbers to appear is not completely obvious. There are two reasons for this: 1. You have set a flag to get the headers / footers to appear in the first place. If this flag is set to false, even if you provide a header or footer, they still will not appear. and 2. The default font size for the header and footer is so small, you can barely see it with the naked eye. So let’s get this figured out.
Api2Pdf is an HTML to PDF API on AWS Lambda. The techniques described below will work for Headless Chrome, but will also work for Api2Pdf. Api2Pdf is a wrapper for Headless Chrome and lets you generate PDFs at massive scale.
Set a header and footer in Headless Chrome
The true source of Headless Chrome’s advanced options lives here on the chrome dev tools documentation: https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF. We also have outlined our own version of it here for Api2Pdf purposes: https://www.api2pdf.com/documentation/advanced-options-headless-chrome/
When using the advanced options you need to consider the following attributes:
- displayHeaderFooter
- headerTemplate
- footerTemplate
displayHeaderFooter is a boolean value and defaults to false. Set this to true. headerTemplate and footerTemplate are string attributes that expect HTML.
And lastly, the font size needs to be properly set.
Below is an footerTemplate example for Headless Chrome in action that also includes page numbers.
<div class=\"page-footer\" style=\"width:100%; text-align:right; font-size:12px;\">Page <span class=\"pageNumber\"></span> of <span class=\"totalPages\"></span></div> |
For Api2Pdf customers, you will want to use a sample payload similar to the following:
{ | |
"html": "<p>Hello World</p>", | |
"inlinePdf": true, | |
"fileName": "test.pdf", | |
"options": { | |
"displayHeaderFooter": true, | |
"footerTemplate": "<div class=\"page-footer\" style=\"width:100%; text-align:right; font-size:12px;\">Page <span class=\"pageNumber\"></span> of <span class=\"totalPages\"></span></div>" | |
} | |
} |
Hope this helps!