[Solution] Custom PDF margin with unknown header/footer heights
-
Re: PDF margin match dynamic header/footer height
Yesterday I opened this topic above and now I've found the solution for that.
Basically, I added the
header-footer
from pdf-utils then I set my custom header and footer inside of each<!-- header-footer --> <body> {{#each $pdf.pages}} {{#if 0}} <div style="page-break-before: always;"></div> {{/if}} <main class="main"> <header class="header"> {{{@root.template.header}}} </header> <footer class="footer"> {{{@root.template.footer}}} </footer> </main> {{/each}} </body>
and on my default template I made this on
script
tag.<!-- main-template --> <script> const header = document.getElementById('main-header'); const footer = document.getElementById('main-footer'); if (header && footer) { const prevOptions = window.JSREPORT_CHROME_PDF_OPTIONS || {}; window.JSREPORT_CHROME_PDF_OPTIONS = { ...prevOptions, marginTop: `${header.offsetHeight + 15}px`, marginBottom: `${footer.offsetHeight + 15}px`, }; } </script>
also, these are my HTML and CSS
<!-- main-template --> <div id="main-header" class="fixed hidden"> {{{template.header}}} </div> <div id="main-footer" class="fixed hidden"> {{{template.footer}}} </div>
// main-template.css .hidden { visibility: hidden; } .fixed { position: fixed; }
The
template.header
andtemplate.footer
I expect to receive as data:// data { "template":{ "header":"<div style='width: 100%; height: 250px; background: green; text-align: center'>HEADER LEGAL</div>", "footer":"<div style='width: 100%; height: 30px; background: red; text-align: center'>FOOTER BACANA {pageNumber}/{pageTotal}</div>" } }
Explanation
The
window.JSREPORT_CHROME_PDF_OPTIONS
works in a dynamic way so if I change it, it will affect my PDF config and update it visually on the generated document.The
main-header
andmain-footer
are invisible and fixed, so they are on "DOM
" and then I'm able to get their heights onscript
tag and set them asmarginTop
andmarginBottom
of my PDF.The reason it HAS to be on
script
is because you don't have access to eitherwindow
ordocument
on script files.
Result
The result is something like this:
If anyone needs an example, I will create one and send as a reply here.