Sebastian Edelmeier
Sebastian Edelmeier

Reputation: 4157

Open PDF blob from Angular Component

In my Angular application, I need to open a PDF when a button is clicked.

I followed the directions given by this post in the first place, so I have these two methods right now:

In the calling component

public PrepareDownload(){
   this._certificateService
            .GetPdf(args)
            .subscribe(
            result => {
                this.BlobUri = URL.createObjectURL(result);
            }
}

public Download() {
    window.open(this.BlobUri);     
}

In the service

public GetPdf() : any  {
  var headers = new Headers();
  headers.append("Content-Type", "application/json");
  var payload = {id:215};
  return this._http.post(this.requestUri, 
                         JSON.stringify(payload), 
                         { headers: headers, 
                           responseType: ResponseContentType.Blob })
                   .map((response: Response) => 
                   {
                      return new Blob([response.blob()], { type: 'application/pdf' });
                   });
}

GetPdf's response contains an array like the following [ 37,80,68,70,45,49,46,...]. Unfortunately, when the download method is called, the result seems to be an invalid pdf. When downloading the file via firefox and renaming it to a txt-file, I can see that the content is not binary but the complete byte array as a string.

enter image description here

Upvotes: 1

Views: 3090

Answers (1)

Sebastian Edelmeier
Sebastian Edelmeier

Reputation: 4157

As indicated in the comments by @David Siro, The Service had to be modified. The request now returns a stream rather than a byte array, which can be handled as described in the question.

Upvotes: 0

Related Questions