0

In my application, I need to download a pdf file by calling an api. The api returns an octet-stream of data, that which I convert that to pdf and download. My download and related things are working fine, but I find that the PDF generated seems to be corrupted. While opening the pdf document, an error logs with the message "Failed to load PDF document". I know the pdf data is corrupted. I had implemented the same in angular 1 which is working fine, but my Ionic 3 code seems to be an error.

Here is my angular 1 code.

$http({
    method: 'POST',
    url: baseurl + 'data/invoice',
    responseType:"arraybuffer",
    transformRequest: transformRequestAsFormPost,
    withCredentials: false,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': AuthToken,
    },
    params: {
        data_id: id,

    }
}).success(function(data, status, headers, config) {
    var arr = data;
    var byteArray = new Uint8Array(arr);
    var a = window.document.createElement('a');

    a.href = window.URL.createObjectURL(
        new Blob([byteArray], { type: 'application/octet-stream' })
    );
    a.download ='MyFileName.pdf' ;

    // Append anchor to body.
    document.body.appendChild(a);
    a.click();

    // Remove anchor from body
    document.body.removeChild(a);


}).error(function(error, status, headers, config) {
    alert("Error")
});

My Ionic 3 code is like this.

Inside http module

fnPostData(method, token, parameters){
    this.tokenString = "Bearer "+token;
    this.postParams = parameters;
    var headers = new Headers();
    headers.append("Accept", 'application/json');
    headers.set("Authorization", this.tokenString);
    headers.set("Content-Type", 'application/x-www-form-urlencoded');
    let options = new RequestOptions({
        headers: headers
    });
    return Observable.create(observer => {
        this.http.post(baseUrl + method, this.postParams, options)
        .map(result => result)
        .subscribe(result => {
           console.log("API Result:", result);
           observer.next(result);
        }, error => { 
          observer.error(error);
        });

    });
}

Inside my component class

generateDataPdf(order) {
    let isToken = 1;
    this.asyncData.fnPostData('data/invoice?data_id='+order.id, this.token, isToken).subscribe((data) => {
        if(data){
            var arr = data;
            var byteArray = new Uint8Array(arr);
            var a = window.document.createElement('a');
            a.href = window.URL.createObjectURL(
                new Blob([byteArray], { type: 'application/octet-stream' })
            );
            a.download ='FileName.pdf';
            // Append anchor to body.
            document.body.appendChild(a);
            a.click();

            // Remove anchor from body
            document.body.removeChild(a);
        }else{
            alert("Error");
        }
    },
    (err) => {
        alert("Error")
    });
}

I know I have missed the following things in the http request.

responseType:"arraybuffer",
transformRequest: transformRequestAsFormPost,
withCredentials: false,

Is it because of this, my pdf data is corrupted? If yes, how can I add this to http request.

Nitheesh
  • 19,238
  • 3
  • 22
  • 49
  • Maybe this answers will help you: 1.) https://stackoverflow.com/questions/45530752/getting-image-from-api-in-angular-4/45630579#45630579 2.) https://stackoverflow.com/questions/47936183/angular-5-file-upload/47938117#47938117 3.) https://stackoverflow.com/questions/45720756/angular4-show-image-from-server/45722275#45722275 – Gregor Doroschenko Jan 30 '18 at 16:36
  • One more thing is, that you should need ``FileReader`` for creating an file to show this in browser. – Gregor Doroschenko Jan 30 '18 at 16:37
  • did you ever find an answer to this? I am trying to use Ionic's http to do the exact same thing and cant seem to find how to set the responseType header to anything (i am trying to set it to blob) – skyleguy Jan 16 '20 at 20:03
  • 1
    @skyleguy I was not able to find a solution. I think, we changed this to a file download from a remote location rather than handling this from client side – Nitheesh Jan 17 '20 at 05:00

0 Answers0