PDF is blank when downloading using javascript

前端 未结 3 1462
天涯浪人
天涯浪人 2020-12-02 13:20

I have a web service that returns PDF file content in its response. I want to download this as a pdf file when user clicks the link. The javascript code that I have written

3条回答
  •  借酒劲吻你
    2020-12-02 13:57

    solved it via XMLHttpRequest and xhr.responseType = 'arraybuffer'; code:

    var xhr = new XMLHttpRequest();
        xhr.open('GET', './api/exportdoc/report_'+id, true);
        xhr.responseType = 'arraybuffer';
        xhr.onload = function(e) {
           if (this.status == 200) {
              var blob=new Blob([this.response], {type:"application/pdf"});
              var link=document.createElement('a');
              link.href=window.URL.createObjectURL(blob);
              link.download="Report_"+new Date()+".pdf";
              link.click();
           }
        };
    xhr.send();
    

提交回复
热议问题