diff --git a/src/generators/HtmlGenerator.js b/src/generators/HtmlGenerator.js
index 103ae0f..1b128e8 100644
--- a/src/generators/HtmlGenerator.js
+++ b/src/generators/HtmlGenerator.js
@@ -9,9 +9,10 @@ const logger = require('../sdk/log4js');
*/
class HtmlGenerator{
- constructor(htmlFilePath, request){
+ constructor(htmlFilePath, request,fileExtension){
this.htmlFilePath=htmlFilePath;
this.request= request;
+ this.fileExtension = fileExtension;
}
@@ -20,14 +21,14 @@ class HtmlGenerator{
var htmlFile = fs.readFileSync(this.htmlFilePath,encodingType);
var mapper = new Mapper(htmlFile, this.request.getContextMap());
var mappedHtml = mapper.replacePlaceholders();
- var mappedHtmlFilePath = this.getReqIdHtmlFilePath();
+ var mappedHtmlFilePath = this.getReqIdHtmlFilePath(this.fileExtension);
fs.writeFileSync(mappedHtmlFilePath,mappedHtml)
logger.debug("HtmlGenerator:generateTempHtmlFile:file written successfully in ms:", Date.now()-startTime)
return mappedHtmlFilePath;
}
getReqIdHtmlFilePath(){
- var tempHtmlFilePath = this.htmlFilePath.replace("index.html", this.request.getRequestId()+".html")
+ var tempHtmlFilePath = this.htmlFilePath.replace("index."+this.fileExtension, this.request.getRequestId()+"."+this.fileExtension)
logger.info("HtmlGenerator:getReqIdHtmlFilePath:the temp filepath formed is", tempHtmlFilePath)
return tempHtmlFilePath;
}
diff --git a/src/helpers/DownloadManager.js b/src/helpers/DownloadManager.js
index d7f8583..9dcb2cb 100644
--- a/src/helpers/DownloadManager.js
+++ b/src/helpers/DownloadManager.js
@@ -13,13 +13,13 @@ class DownloadManager {
}
- downloadFile(callback) {
+ downloadFile(fileExtension, callback) {
request
.get(this.downloadParams.getSourceUrl())
.on('error', function (error) {
logger.error("DownloadManager:downloadFile:",error);
})
- .pipe(fs.createWriteStream(this.downloadParams.getDownloadPath()))
+ .pipe(fs.createWriteStream(this.downloadParams.getDownloadPath(fileExtension)))
.on('finish', function () {
logger.info('finished dowloading');
callback(null)
diff --git a/src/helpers/DownloadParams.js b/src/helpers/DownloadParams.js
index 32be084..4bd3b54 100644
--- a/src/helpers/DownloadParams.js
+++ b/src/helpers/DownloadParams.js
@@ -31,9 +31,9 @@ class DownloadParams {
}
- getHtmlPath() {
- const htmlPath = this.CERT_DOWNLOAD_FOLDER.concat(this.getFileName().replace(".zip", "/index.html"))
- logger.info("DownloadParams:getHtmlPath:index.html file path is:", htmlPath)
+ getHtmlPath(fileExtension) {
+ const htmlPath = this.CERT_DOWNLOAD_FOLDER.concat(this.getFileName().replace(".zip", "/index." + fileExtension))
+ logger.info("DownloadParams:getHtmlPath:index." + fileExtension + " file path is:"+htmlPath)
return htmlPath;
diff --git a/src/helpers/FileExtractor.js b/src/helpers/FileExtractor.js
index 9263b17..9be01ec 100644
--- a/src/helpers/FileExtractor.js
+++ b/src/helpers/FileExtractor.js
@@ -17,13 +17,13 @@ class FileExtactor {
* this method will extract the zip file and return the absolute path file uri.
* @param {*} callback
*/
- extractZipFile(callback) {
+ extractZipFile(fileExtension, callback) {
const startTime = Date.now();
var zip = new admZip(this.downloadParams.getDownloadPath());
logger.info('FileExtractor:extractZipFile:start unzip at path', this.downloadParams.getFileExtractToPath());
zip.extractAllTo(this.downloadParams.getFileExtractToPath(), true);
logger.debug('FileExtractor:extractZipFile:finished unzip in secs:', Date.now() - startTime);
- callback(null,filemanager.getAbsolutePath(this.downloadParams.getHtmlPath()))
+ callback(null,filemanager.getAbsolutePath(this.downloadParams.getHtmlPath(fileExtension)))
}
}
diff --git a/src/helpers/TemplateProcessor.js b/src/helpers/TemplateProcessor.js
index 7efb4f2..d929ac8 100644
--- a/src/helpers/TemplateProcessor.js
+++ b/src/helpers/TemplateProcessor.js
@@ -18,19 +18,19 @@ class TemplateProcessor {
this.downloadParams = downloadParams;
}
- processTemplate() {
+ processTemplate(fileExtension) {
var downloadManager = new DownloadManager(this.downloadParams)
var fileExtractor = new FileExtactor(this.downloadParams)
- var htmlAbsFilePath = filemanager.getAbsolutePath(this.downloadParams.getHtmlPath())
+ var htmlAbsFilePath = filemanager.getAbsolutePath(this.downloadParams.getHtmlPath(fileExtension))
var fileCheckResult = this.checkFileExists(htmlAbsFilePath)
if(!fileCheckResult) {
return new Promise(function (resolve, reject) {
async.waterfall([
(callback) => {
- downloadManager.downloadFile(callback);
+ downloadManager.downloadFile(fileExtension, callback);
},
(callback2) => {
- fileExtractor.extractZipFile(callback2)
+ fileExtractor.extractZipFile(fileExtension, callback2)
}
], (err, result) => {
diff --git a/src/package.json b/src/package.json
index 8464ad3..aec6826 100644
--- a/src/package.json
+++ b/src/package.json
@@ -18,7 +18,8 @@
"superagent": "^5.2.2",
"util": "^0.12.2",
"uuid": "~3.2.1",
- "velocityjs": "^2.0.0"
+ "velocityjs": "^2.0.0",
+ "svg2png": "^4.1.1"
},
"devDependencies": {},
"scripts": {
diff --git a/src/routes/index.js b/src/routes/index.js
index 62e954e..f3e3ea0 100644
--- a/src/routes/index.js
+++ b/src/routes/index.js
@@ -4,7 +4,9 @@ const express = require('express'),
router.post('/v1/print/preview/generate', (req, res) => printService.generate(req, res));
-router.post('/v1/print/pdf', (req, res) => printService.printPdf(req, res));
+router.post('/v1/print/pdf', (req, res) => printService.printPdf(req, res, 'html'));
+
+router.post('/v1/print/png', (req, res) => printService.printPdf(req, res, 'svg'));
router.get('/health', (req, res) => printService.health(req, res));
diff --git a/src/service/print-service.js b/src/service/print-service.js
index f6ecf90..b1685a4 100644
--- a/src/service/print-service.js
+++ b/src/service/print-service.js
@@ -14,6 +14,8 @@ const uuidv1 = require('uuid/v1'),
serviceName = 'print-service/',
StorageParams = require('../helpers/StorageParams'),
util = require('util');
+ fs = require("fs");
+ svg2png = require("svg2png");
class PrintService {
@@ -38,29 +40,56 @@ class PrintService {
})();
}
- printPdf(req, res) {
+ printPdf(req, res, fileExtension) {
(async () => {
try {
this.validateRequest(res, req.body.request)
var request = this.getComposedRequest(req.body.request);
var dowloadParams = new DownloadParams(request.getHtmlTemplate())
- var templateProcessor = new TemplateProcessor(dowloadParams)
- var dataPromise = templateProcessor.processTemplate()
- dataPromise.then(async htmlFilePath => {
- logger.info("PrintService:printPdg:the index html file got:", htmlFilePath)
- var htmlGenerator = new HtmlGenerator(htmlFilePath, request);
- var mappedHtmlFilePath = htmlGenerator.generateTempHtmlFile()
- const page = await this.browser.newPage();
- await page.goto("file://" + mappedHtmlFilePath, { waitUntil: 'networkidle0' })
- const pdfFilePath = filemanager.getAbsolutePath(dowloadParams.getFileExtractToPath()) + request.getRequestId() + '.pdf';
- await page.pdf({
- path: pdfFilePath, format: 'A4', printBackground: true
- });
- page.close()
- const destPath = request.getStorageParams().getPath() + path.basename(pdfFilePath);
- const pdfUrl = await this.uploadBlob(this.config.azureAccountName, request.getStorageParams().getContainerName(), destPath, pdfFilePath);
- this.sendSuccess(res, { id: constants.apiIds.PRINT_API_ID }, { pdfUrl: pdfUrl, ttl: 600 });
- this.sweepFiles([mappedHtmlFilePath, pdfFilePath])
+ var templateProcessor = new TemplateProcessor(dowloadParams, fileExtension)
+ var dataPromise = templateProcessor.processTemplate(fileExtension)
+ dataPromise.then(async sourceFilePath => {
+ var htmlGenerator = new HtmlGenerator(sourceFilePath, request, fileExtension);
+ var mappedSourceFilePath = htmlGenerator.generateTempHtmlFile()
+ var destFilePath = '';
+ if(fileExtension == 'html') {
+ logger.info("PrintService:printPDF:the index html file got:", sourceFilePath)
+ destFilePath = filemanager.getAbsolutePath(dowloadParams.getFileExtractToPath()) + request.getRequestId() + '.pdf';
+ const page = await this.browser.newPage();
+ await page.goto("file://" + mappedSourceFilePath, { waitUntil: 'networkidle0' })
+ await page.pdf({
+ path: destFilePath, format: 'A4', printBackground: true
+ });
+ page.close()
+ } else if(fileExtension == 'svg') {
+ logger.info("PrintService:printPNG:the index svg file got:", sourceFilePath)
+ destFilePath = filemanager.getAbsolutePath(dowloadParams.getFileExtractToPath()) + request.getRequestId() + '.png';
+ const fileOptions = {
+ file: mappedSourceFilePath,
+ includeFilename: true, // for external files for eg: images, fonts to render
+ options: {
+ filename: mappedSourceFilePath,
+ width: 842,
+ height: 593
+ }
+ }
+ var input = fs.readFileSync(fileOptions.file)
+ await svg2png(input, fileOptions.options)
+ .then(buffer => {
+ fs.writeFileSync(destFilePath, buffer)
+ })
+ .catch(e => console.error(`\n\n${e.stack}\n\n\n`));
+ }
+ const destPath = request.getStorageParams().getPath() + path.basename(destFilePath);
+ const destFileUrl = await this.uploadBlob(this.config.azureAccountName, request.getStorageParams().getContainerName(), destPath, destFilePath);
+ var uploadRes = {};
+ if(fileExtension == 'html') {
+ uploadRes = { pdfUrl: destFileUrl, ttl: 600 }
+ } else if(fileExtension == 'svg') {
+ uploadRes = { pngUrl: destFileUrl, ttl: 600 }
+ }
+ this.sendSuccess(res, { id: constants.apiIds.PRINT_API_ID }, uploadRes);
+ this.sweepFiles([mappedSourceFilePath, destFilePath])
}, function (err) {
logger.error("PrintService:error got:", err);
this.sendServerError(res, { id: constants.apiIds.PRINT_API_ID });