Get PDFKit as base64 string

rekam picture rekam · Aug 25, 2016 · Viewed 7.2k times · Source

I'm searching a way to get the base64 string representation of a PDFKit document. I cant' find the right way to do it...

Something like this would be extremely convenient.

var doc = new PDFDocument();
doc.addPage();

doc.outputBase64(function (err, pdfAsText) {
    console.log('Base64 PDF representation', pdfAsText);
});

I already tried with blob-stream lib, but it doesn't work on a node server (It says that Blob doesn't exist).

Thanks for your help!

Answer

Grant Palin picture Grant Palin · Sep 15, 2016

I was in a similar predicament, wanting to generate PDF on the fly without having temporary files lying around. My context is a NodeJS API layer (using Express) which is interacted with via a React frontend.

Ironically, a similar discussion for Meteor helped me get to where I needed. Based on that, my solution resembles:

const PDFDocument = require('pdfkit');
const { Base64Encode } = require('base64-stream');

// ...

var doc = new PDFDocument();

// write to PDF

var finalString = ''; // contains the base64 string
var stream = doc.pipe(new Base64Encode());

doc.end(); // will trigger the stream to end

stream.on('data', function(chunk) {
    finalString += chunk;
});

stream.on('end', function() {
    // the stream is at its end, so push the resulting base64 string to the response
    res.json(finalString);
});