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

后端 未结 8 1648
悲哀的现实
悲哀的现实 2020-11-22 14:33

I am trying to build a PDF file out of a binary stream which I receive as a response from an Ajax request.

Via XmlHttpRequest I receive the following da

8条回答
  •  难免孤独
    2020-11-22 15:09

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

提交回复
热议问题