When printing to PDF the management of header and footer is a pain.
Anvil feeds a form to an headless Chrome which renders it and prints it to PDF. The problem is that browsers are good at managing one long page, not so good at splitting that one long page in multiple pages, each with its own header and footer.
I did some research, and the most hopeful info I found was this post that suggests to use a table, because that’s the only element with header and footer recognized by browsers.
So I created an app with a custom HTML template that allows to drop 3 custom components, one for the header, one for the body and one for the footer.
Rendering the form on the browser will show the header on top, then the body, then the footer at the end.
Rendering to PFD shows the header and the footer on each page as expected. Yay!
There are a few minor problems:
- The footer on the last page is at the end of the table, not at the bottom of the page
- The styles that come with Anvil and the media queries do not target
table
elements, so you may end up with unexpected results. If you are picky, you may need to play with the css - The background color of the body will be used for the header on pages 2+. This is rarely a problem because a background color is rarely used, but it’s good to know
- Using
tfoot {position: fixed; bottom: 0;}
to keep the footer at the bottom of the page works with the footer, but the body doesn’t know about it and will spill and overlap into the footer and the header will not be in pages 2+. Weird
So I decided to proceed keeping in mind these limitations and created a working example:
https://anvil.works/build#clone:Z27C6XT7JSYS737L=TGME7LPQ452WC63NQ6G42MZP
The interesting parts are:
- The
PdfPage
form - a custom HTML form with atable
with slots defined to accept components in thethead
,tbody
andtfoot
elements - The 3 forms
PdfHeader
,PdfBody
andPdfFooter
dragged into the respective slots - The first few lines of theme.css - they are mostly commented out because usually useless
- The margins are set in the
PdfGenerator
server module - it’s commented out because usually useless - The 3rd party dependency to Anvil Extras allows to use the
PageBreak
custom component