Hack for adding data handling to Chrome-PDF header/footer



  • 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:

    1. Add a template (let's call it DynamicHeaderTemplate) with your header template, including dynamic data-handling tags.
    2. 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.



  • Thanks for sharing. However, isn't this actually the same as you would put to the chrome native header this?

    {#child DynamicHeaderTemplate}
    

    Of course, you have more control with script, but for common situation using child template should be enough.



  • you are a saint!


Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.