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

后端 未结 8 1721
悲哀的现实
悲哀的现实 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:00

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

提交回复
热议问题