Lee
Lee

Reputation: 533

How can make a proper callback on pdfkit PDF file generation in Node.js?

I am calling a function that generates a PDF and gets me its path. On the callback I'm sending the PDF to the user to download it. Calling:

create_pdf(data, function(path) {
 res.download(path) 
})

And this is the function:

const PDFDocument = require('pdfkit')
function create_pdf(input, callback) {
    let doc = new PDFDocument({ margin: 0 })
    doc.fillColor('Black').fontSize(22)
        .font('Scandia-bold')
        .text(input, 167, 265, {
            align: 'center',
            width: 280
        })
    doc.on('end', function() { callback(path) })
    doc.end()
}

But what the user ends up downloading is always a corrupt/damaged PDF while the PDF generated on the server is very fine. Is the problem that my function is sending the path before PDF creation is finished (aka my callback code is wrong)? Or what?

Upvotes: 1

Views: 2325

Answers (2)

F.H.
F.H.

Reputation: 1684

If you want to use async/await you could do something like this

await ((path) => {
    return new Promise(resolve => {
        writeStream.on('finish', () => {
            resolve(path);
        });
    });
})(path);

Upvotes: 0

Lee
Lee

Reputation: 533

Never mind :) Within the function I had to identify a 'writeStream' and then do the callback when it finishes:

writeStream = fs.createWriteStream(path)
doc.pipe(writeStream)

writeStream.on('finish', function () {
    callback(path)
})

Upvotes: 1

Related Questions