One issue I was struggling with was how to add dynamic data to headers/footers in Chrome-PDF without having to resort to using pdf-tools, which are slow and extremely inefficient for long documents using the same data. I've found a nice little hack that allows me to do so now:
- Add a template (let's call it DynamicHeaderTemplate) with your header template, including dynamic data-handling tags.
- Add a script (let's call it DynamicHeaderScript) and reference it from your main template with the following code:
const proxy = require('jsreport-proxy');
var headerTemplate = null;
async function beforeRender(req, res) {
if (!req.context.isChildRequest) {
if (headerTemplate === null) {
const result = await proxy.render({ template: { name: 'DynamicHeaderTemplate', recipe: 'html' }, data: req.data });
headerTemplate = result.content.toString();
}
req.template.chrome.headerTemplate = headerTemplate;
}
}
What this essentially does is calls the DynamicHeaderTemplate template before render, with the data structure for your main template. The resulting HTML replaces the chrome-pdf header html.