Reputation: 3967
I am trying to use PDFKit to generate a PDF, and then return it as a base64 string.
Here is my code:
function buildPDFStructure(data){
let doc = new PDFDocument();
var bufferChunks = [];
doc.on('readable', function () {
// Store buffer chunk to array
bufferChunks.push(doc.read());
});
doc.on('end', ()=> {
var pdfBuffer = Buffer.concat(bufferChunks),
pdfBase64String = pdfBuffer.toString('base64');
// This is a string
return Promise.resolve(pdfBase64String);
});
for(var i=0; i<data.length; i++){
doc.text(data[i].text);
}
doc.end();
}
data
is an array that works fine for
the for loop.
The problem is - that the function above seems to not return the promise. Instead, I receive .then() of undefined
error, which I think is caused because nothing is returned from the function. What am I doing wrong?
Upvotes: 2
Views: 1901
Reputation: 11
try this
function buildPDFStructure(data){
return new Promise((resolve, reject) => {
try {
let doc = new PDFDocument();
var bufferChunks = [];
doc.on('readable', function () {
// Store buffer chunk to array
bufferChunks.push(doc.read());
});
doc.on('end', ()=> {
var pdfBuffer = Buffer.concat(bufferChunks),
pdfBase64String = pdfBuffer.toString('base64');
// This is a string
resolve(pdfBase64String);
});
for(var i=0; i<data.length; i++){
doc.text(data[i].text);
}
doc.end();
} catch (e) {
console.error(e);
reject(e);
}
});
}
Upvotes: 1