简体   繁体   中英

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.

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM