Have you ever had a situation where you are possibly generating a PDF from the server side via async technologies like jquery or Angular and you want to push that binary data right to the browser as to mimic a download of a file?

I have had many occasions where this has happened and I found a little trick that works great, and it’s simple.

Let’s assume you make an async call like jquery’s $.ajax or Angular’s $http service.  Normally, you provide some callback function and from there, you get back some form of data, typically in JSON format.  The issue is, you need to take that JSON data and stream it right back to the browser allowing the default browser client to open the file based on the media type (ie PDF), or in some cases, simply download it.  This trick will get the data (however that may be) and create a hyperlink element right on the DOM, attaches the binary content from the JSON structure into a Blob object, and then triggers the click event on the newly created hyperlink, similar to someone clicking a link on a page to download a PDF.

Feel free to write the code to remove the hyperlink since it may be sitting on the DOM unnecessarily.

-- your callback function here
 a = document.createElement('a');
 a.download = 'somefilename.pdf';
 a.type = 'application/pdf';
 blob = new Blob([yourJSONString.pdfdata], {"type": "application/pdf"});
 a.href = (window.URL || webkitURL).createObjectURL(blob);
 a.click();

And there you have it. A very useful way to easily trigger your browser to handle files in an asynchronous mode.  Let me know how you make out with this.