4

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.

Mohamed Gara
  • 2,665
  • 3
  • 13
  • 19
Uzair Khan
  • 2,812
  • 7
  • 30
  • 48
  • What is `pdfContent`? – guest271314 Jun 09 '17 at 00:04
  • Its an encrypted string, which comes in '_body' of response. – Uzair Khan Jun 09 '17 at 00:08
  • Why do you expect an "encrypted string" to result in a `.pdf` file? Is the string an "encrypted string" or `base64` string? – guest271314 Jun 09 '17 at 00:16
  • At first glance the data does appear to be "encrypted". You can request the data as a `Blob` or `ArrayBuffer`, see [How to build PDF file from binary string returned from a web-service using javascript](https://stackoverflow.com/questions/12876000/how-to-build-pdf-file-from-binary-string-returned-from-a-web-service-using-javas/), [Displaying pdf from arraybuffer](https://stackoverflow.com/questions/42106584/displaying-pdf-from-arraybuffer/) – guest271314 Jun 09 '17 at 00:23
  • It seems that file saver can't convert to pdf. https://github.com/eligrey/FileSaver.js/issues/186 – Daniel Ormeño Jun 09 '17 at 05:07

2 Answers2

2

  import 'rxjs/Rx' ;




this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
                 error => console.log("Error downloading the file."),
                 () => console.info("OK");
                 
   When the request is ready it will call the function "downloadFile" that is defined as follows
downloadFile(data: Response){
  var blob = new Blob([data], { type: 'text/csv' });
  var url= window.URL.createObjectURL(blob);
  window.open(url);
}
Always Learn
  • 662
  • 6
  • 14
2

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';
Uzair Khan
  • 2,812
  • 7
  • 30
  • 48