I want to download a file in pdf in Angular 2, I am using FileSaver.js
to save the file as pdf.
(response) => {
var mediaType = 'application/pdf';
let pdfContent = response["_body"];
var blob = new Blob([pdfContent], {type: mediaType});
var filename = 'test.pdf';
//setTimeout(FileSaver.saveAs(blob, filename),10000); //Tried this but no result
// FileSaver.saveAs(blob(), "docitt-report-" + documentNo + ".pdf"); //tried this too
},
But the downloaded pdf file is empty, I thought maybe the resource is taking time so I tried with setTimeout
, but it still didn't help. Though there is data in the response which I could see in console as response._body
.
Let me know where I'm going wrong.
I got it to work, and this is my answer below:
downloadDocument(docId){
const headers = new Headers({responseType:ResponseContentType.Blob});
headers.append('authorization','Bearer '+token);
this.http.get(url,{headers:headers,responseType:ResponseContentType.Blob}).subscribe(
(response) => {
FileSaver.saveAs(response.blob(), "Document-" + docId+ ".pdf");
}
);
}
Import FilSaver
import * as FileSaver from 'file-saver';