Sunday, 9 April 2017

Add png image in pdf with nodejs and jspdf

I am pretty new to nodeJs and I am trying create a pdf with jsPdf on server.

I have installed the jspdf using npm install jspdf --save

As nodeJs doest have support for atob which was used in jspdf, I have added

npm install atob --save and added

var atob = require('atob');
var PNG = require('png-js');

where png-js is required for adding png files in jspdf. When I try to add the PNG file to the pdf with following code

let imgData=request.payload.canvasobj;
let pdfContent = new jsPDF();
pdfContent.addImage(imgData, 'PNG',  40, 20, 0, 0);
let data = pdfContent.output('arraybuffer');
let buffer = Buffer.from(data);
let arraybuffer = Uint8Array.from(buffer);
fs.appendFile('./canvas.pdf', new Buffer(arraybuffer), function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log("PDF created");
    }
});

the following error is triggered

Debug: internal, implementation, error
    TypeError: Uncaught error: Cannot read property 'buffer' of undefined
    at Object.jsPDFAPI.processPNG (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\jspdf\dist\jspdf.debug.js:8796:80)
    at Object.jsPDFAPI.addImage (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\jspdf\dist\jspdf.debug.js:4696:50)
    at canvas (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\requestHandler.js:105:16)
    at Object.internals.handler (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\hapi\lib\handler.js:99:36)
    at request._protect.run (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\hapi\lib\handler.js:30:23)
    at internals.Protect.run (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\hapi\lib\protect.js:59:12)
    at exports.execute (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\hapi\lib\handler.js:24:22)
    at each (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\hapi\lib\request.js:382:16)
    at iterate (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\hapi\node_modules\items\lib\index.js:36:13)
    at done (C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\hapi\node_modules\items\lib\index.js:28:25)
Debug: internal, implementation, error
    TypeError: fn is not a function
    at C:\LearningPro\NodeJsProjects\pdfexport-nodejs\node_modules\png-js\png-node.js:246:16
    at Inflate.onEnd (zlib.js:227:5)
    at emitNone (events.js:91:20)
    at Inflate.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:974:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickDomainCallback (internal/process/next_tick.js:122:9)

What do I am missing out? It works fine with JPEG Image.



via DharanBro

No comments:

Post a Comment