Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ISSUE#SC-1801: Added new end point to convert svg to png #16

Open
wants to merge 2 commits into
base: release-3.0.0
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/generators/HtmlGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}


Expand All @@ -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;
}
Expand Down
4 changes: 2 additions & 2 deletions src/helpers/DownloadManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions src/helpers/DownloadParams.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;


Expand Down
4 changes: 2 additions & 2 deletions src/helpers/FileExtractor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/helpers/TemplateProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down
3 changes: 2 additions & 1 deletion src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
4 changes: 3 additions & 1 deletion src/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));

Expand Down
65 changes: 47 additions & 18 deletions src/service/print-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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 });
Expand Down