From 60de951991b2e3a3aaebe908f53239266b1145e6 Mon Sep 17 00:00:00 2001 From: aishwa8141 Date: Wed, 10 Jun 2020 19:02:13 +0530 Subject: [PATCH 1/2] ISSUE#SC-1801: added svg2png convertion --- src/generators/HtmlGenerator.js | 7 ++-- src/helpers/DownloadManager.js | 4 +- src/helpers/DownloadParams.js | 6 +-- src/helpers/FileExtractor.js | 4 +- src/helpers/TemplateProcessor.js | 9 +++-- src/package.json | 3 +- src/routes/index.js | 4 +- src/service/print-service.js | 63 +++++++++++++++++++++++--------- 8 files changed, 67 insertions(+), 33 deletions(-) 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..801c6e7 100644 --- a/src/helpers/TemplateProcessor.js +++ b/src/helpers/TemplateProcessor.js @@ -14,23 +14,24 @@ const fs = require('fs') class TemplateProcessor { - constructor(downloadParams) { + constructor(downloadParams, fileExtension) { this.downloadParams = downloadParams; + this.fileExtension = fileExtension } processTemplate() { 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(this.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..f2fde1f 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 templateProcessor = new TemplateProcessor(dowloadParams, fileExtension) 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]) + 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 }); From 4a0832e3659fd274c744535778d50140922dda9b Mon Sep 17 00:00:00 2001 From: aishwa8141 Date: Thu, 11 Jun 2020 15:16:20 +0530 Subject: [PATCH 2/2] added new end point /v1/print/png --- src/helpers/TemplateProcessor.js | 7 +++---- src/service/print-service.js | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/helpers/TemplateProcessor.js b/src/helpers/TemplateProcessor.js index 801c6e7..d929ac8 100644 --- a/src/helpers/TemplateProcessor.js +++ b/src/helpers/TemplateProcessor.js @@ -14,15 +14,14 @@ const fs = require('fs') class TemplateProcessor { - constructor(downloadParams, fileExtension) { + constructor(downloadParams) { this.downloadParams = downloadParams; - this.fileExtension = fileExtension } - processTemplate() { + processTemplate(fileExtension) { var downloadManager = new DownloadManager(this.downloadParams) var fileExtractor = new FileExtactor(this.downloadParams) - var htmlAbsFilePath = filemanager.getAbsolutePath(this.downloadParams.getHtmlPath(this.fileExtension)) + var htmlAbsFilePath = filemanager.getAbsolutePath(this.downloadParams.getHtmlPath(fileExtension)) var fileCheckResult = this.checkFileExists(htmlAbsFilePath) if(!fileCheckResult) { return new Promise(function (resolve, reject) { diff --git a/src/service/print-service.js b/src/service/print-service.js index f2fde1f..b1685a4 100644 --- a/src/service/print-service.js +++ b/src/service/print-service.js @@ -47,7 +47,7 @@ class PrintService { var request = this.getComposedRequest(req.body.request); var dowloadParams = new DownloadParams(request.getHtmlTemplate()) var templateProcessor = new TemplateProcessor(dowloadParams, fileExtension) - var dataPromise = templateProcessor.processTemplate() + var dataPromise = templateProcessor.processTemplate(fileExtension) dataPromise.then(async sourceFilePath => { var htmlGenerator = new HtmlGenerator(sourceFilePath, request, fileExtension); var mappedSourceFilePath = htmlGenerator.generateTempHtmlFile()