Generating PDF and returning it as base64 from function - pdfkit

1.7k views Asked by At

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?

1

There are 1 answers

0
Daniel Placido On

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);
        }
    });
}