Search code examples
angular2-services

How to download pdf file in angular 2


This is function to download pdf file in angular 2 when I am downloading Pdf file it is corrupted file. So how do I solve this problem. It is displaying corrupted data like this. %PDF-1.5 %���� ↵66 0 obj <> endobj

downloadFile() {
    //this.http.get('https://contactsapi.apispark.net/v1/companies/').subscribe(
    this.http.get('assets/Files/booking.pdf').subscribe(
      (response: any) => {
        console.log(response);
        let parsedResponse =(response)
        var blob = new Blob([response], {type: 'application/pdf'});
        var filename = 'booking.pdf';
        saveAs(blob, filename);
      });
  }

Solution

  • we need this package file-saver,you install like "npm install file-saver --save", then you can try like this

     public downloadCSVFile(){
        this.downloadPdf().subscribe(
            (res) => {      
                saveAs(res,'test.pdf')
            }
        );
    
    
    }
    
    public downloadPdf(): any {
        let url='your url'
        let headers = new Headers();
        headers.append('Authorization', 'JWT ' + localStorage.getItem('id_token'));
        return this.http.get(url,{  headers: headers,responseType: ResponseContentType.Blob }).map(
            (res) => {
                return new Blob([res.blob()], { type: 'application/pdf' })
            })
    }