var ejs = require('ejs');
var fs = require('fs');
var pdf = require('html-pdf');
const mysql = require('mysql');
/**
* Class for generating pdf reports based on ejs templates
*
* 1. initialize class instance
* 2. setTemplate with ejs template parameter
* 3. setData
* 4. setOutputFile (name of pdf-File)
* 5. call generatePDFDocumentForReport with callback
*/
class reports {
constructor(logger) {
// initialize instance properties
this.logger = logger;
this.appRoot = require('app-root-path');
this.reportingBasePath = this.appRoot + "/public/reports/";
this.logger.debug('MODELS-REPORTING | initialising Reporting Module');
}
setData(data) {
this.data = data;
}
setTemplate(template) {
this.template = template;
}
setOutPutFile(outputfile) {
this.outputfile = outputfile;
}
generateHTMLDocumentForReport(req, res, callback) {
if (this.data != null) {
this.data.basepath = req.protocol + '://' + req.headers.host;
var template = fs.readFileSync(this.reportingBasePath + 'templates/' + this.template, 'utf8');
var html = "Error";
try {
html = ejs.render ( template , { reportdata: this.data } );
} catch (err) {
req.app.logger.error('MODELS-REPORTS | Error rendering Report Template: ' + err.message);
}
try {
fs.writeFileSync(this.reportingBasePath + "ondemand/" + this.template + ".html", html, 'utf8');
req.app.logger.debug('MODELS-REPORTS | Successfully generated HtML report');
callback(false);
} catch (err) {
req.app.logger.error('MODELS-REPORTS | Error generating HTML report: ' + err.message);
callback(err);
}
} else {
callback(true);
}
}
generatePDFDocumentForReport(req, res, callback) {
var html = fs.readFileSync(this.reportingBasePath + 'ondemand/' + this.template + '.html', 'utf8');
var options = {
format: 'A4',
border: '5mm'
};
pdf.create(html, options).toFile(this.reportingBasePath + 'ondemand/' + this.outputfile, function(err, res) {
if (err) {
req.app.logger.error('MODELS-REPORTS | Error generating PDF report: ' + err.message);
callback(err);
} else {
req.app.logger.debug('MODELS-REPORTS | Successfully generated pdf report at path: ' + res);
callback();
}
});
}
}
// export the class
module.exports = reports;