Have you ever come across a situation where you want to make an asynchronous call from your client (ie a browser) to the server, where the server returns an array of Base64 encoded bytes but you need to automatically send the PDF to the browser?  It’s actually quite easy to do, so here’s how you do it.

Assume you have a callback method (ie a success method) in your Javascript code that accepts a response object of some kind.  Since there are so many asynchronous libraries on the market, I’ll assume you know how your Javascript client can handle a successful async response.


var callback = function(response) {...}

Inside of this function we simply execute the following, assuming we are getting back Base64 Encoded data and we want to stream a PDF.

var a = document.createElement('a');
var pdfAsDataUri = "data:application/pdf;base64,"+response.data;
a.download = 'export.pdf';
a.type = 'application/pdf';
a.href = pdfAsDataUri;

This code will create a DOM element for a hyperlink, use a fancy way to inline the byte data in a String (prefixed with the mime type and the indicator to tell the browser the data is Base64 encoded, a filename called whatever you wish, and once again the mime type for the anchor/hyperlink.  We then simulate a click of this dynamic link to send the PDF contents to the browser so it knows how to display or download PDFs.

Pretty cool!