How to build PDF file from binary string returned from a web-service using javascript How to build PDF file from binary string returned from a web-service using javascript javascript javascript

How to build PDF file from binary string returned from a web-service using javascript


Is there any solution like building a pdf file on file system in order to let the user download it?

Try setting responseType of XMLHttpRequest to blob , substituting download attribute at a element for window.open to allow download of response from XMLHttpRequest as .pdf file

var request = new XMLHttpRequest();request.open("GET", "/path/to/pdf", true); request.responseType = "blob";request.onload = function (e) {    if (this.status === 200) {        // `blob` response        console.log(this.response);        // create `objectURL` of `this.response` : `.pdf` as `Blob`        var file = window.URL.createObjectURL(this.response);        var a = document.createElement("a");        a.href = file;        a.download = this.response.name || "detailPDF";        document.body.appendChild(a);        a.click();        // remove `a` following `Save As` dialog,         // `window` regains `focus`        window.onfocus = function () {                               document.body.removeChild(a)        }    };};request.send();


I realize this is a rather old question, but here's the solution I came up with today:

doSomethingToRequestData().then(function(downloadedFile) {  // create a download anchor tag  var downloadLink      = document.createElement('a');  downloadLink.target   = '_blank';  downloadLink.download = 'name_to_give_saved_file.pdf';  // convert downloaded data to a Blob  var blob = new Blob([downloadedFile.data], { type: 'application/pdf' });  // create an object URL from the Blob  var URL = window.URL || window.webkitURL;  var downloadUrl = URL.createObjectURL(blob);  // set object URL as the anchor's href  downloadLink.href = downloadUrl;  // append the anchor to document body  document.body.append(downloadLink);  // fire a click event on the anchor  downloadLink.click();  // cleanup: remove element and revoke object URL  document.body.removeChild(downloadLink);  URL.revokeObjectURL(downloadUrl);}


I changed this:

var htmlText = '<embed width=100% height=100%'                 + ' type="application/pdf"'                 + ' src="data:application/pdf,'                 + escape(pdfText)                 + '"></embed>'; 

to

var htmlText = '<embed width=100% height=100%'                 + ' type="application/pdf"'                 + ' src="data:application/pdf;base64,'                 + escape(pdfText)                 + '"></embed>'; 

and it worked for me.