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.