Demo: Rendering reports on the server with Node.js and jsreports

Here’s a quick example of how to run reports on the server using Node.js.  The way it works is simple:

  1. Import the jsreports-server module from the jsreports distribution,
  2. Load your report definition and data source JSON files just like you would in the browser, and
  3. Call server.export() on a new Server instance.

Important: before running your script, you’ll need to install the phantomjs-prebuilt package:

npm install -g phantomjs-prebuilt

Here’s some sample code showing how easy it is:

var fs = require('fs');
var path = require('path');

// Import the jsreports server package
var jsreports = require('./lib/jsreports/jsreports-server.js');

var server = new jsreports.Server();

// Load the report from a .json file on disk
var report = require('./reports/report.json');

// For demo purposes only; returns an array of data source configurations, just as in the browser
var datasets = require('./datasets.js');

// Call server.export() just like you would call jsreports.export() in the browser
server.export({
   format: 'PDF',
   report_def: report,
   datasets: datasets,
   // Must provide a file:// base URL to prepend to the image URLs in the report, 
   // in order to locate them on the server - here, use the current directory
   imageUrlPrefix: 'file://' + path.resolve(__dirname) + '/'
}, function(err, pdfStream) {
  if (err) return console.error(err);
  // Got the output stream - write PDF to file
  var outPath = path.resolve(__dirname, 'out-' + (new Date()).getTime() + '.pdf');
  var outStream = fs.createWriteStream(outPath, 'utf8');
  pdfStream.on('end', function() { 
    console.log('Wrote PDF to', outPath);
    server.stop();
  });
  pdfStream.pipe(outStream);
});

Call server.stop() when you’re done rendering.  If you don’t, the Server instance will remain running to serve future requests.  By default, up to 3 worker processes will handle reports in parallel as needed.

As always, get in touch with us at support@jsreports.com if you have any questions!