Search code examples
jsreport

how to append files with jsreport-core


I read in https://jsreport.net/learn/pdf-utils but I didn't find the answer to how to append files via scripts when not using the js report studio.

this is my code:

main.js

const jsreport = require('jsreport-core')();
const fs = require('fs');
const d = require('./child');
const foo = async() => {
    await jsreport.init();
    const resp = await jsreport.render({
        template: {
            content: '<h1>Hello {{foo}}</h1>',
            engine: 'handlebars',
            recipe: 'chrome-pdf'
        },
        data: {
            foo: "1"
        }
    });
    fs.writeFileSync('jsreport.pdf', resp.content);
    process.exit();
}

foo();

child.js

module.exports = function beforeRender(req, res, done) {
    req.template.content = req.template.content('1', '2')
    done();
}

Solution

  • const jsreport = require('jsreport-core')()
    jsreport.use(require('jsreport-chrome-pdf')())
    jsreport.use(require('jsreport-pdf-utils')())
    jsreport.use(require('jsreport-handlebars')())
    const fs = require('fs').promises
    
    ;(async () => {
      await jsreport.init()
      const response = await jsreport.render({
        template: {
          content: 'Hello from main report',
          engine: 'handlebars',
          recipe: 'chrome-pdf',
          pdfOperations: [{
            type: 'append',
            template: {
              engine: 'handlebars',
              recipe: 'chrome-pdf',
              content: 'Content to append'
            }
          }]
        }
      })
    
      await fs.writeFile('out.pdf', response.content)
      await jsreport.close()
    })()
    

    I recommend checking the particular repository unit tests, there always many examples.