简体   繁体   中英

In Angular 5 how can I force a download of a PDF retrieved from an authenticated API

I have an API endpoint which uses authentication. The endpoint is a GET endpoint however I can not simply load it into a browser because the endpoint is looking for an authentication token in the header. So. In order to get the data from the endpoint I have created a service (which uses an extension of the httpClient object that automatically puts in the proper authentication headers. This is how my service call looks (simplified):

getReceipt(): Observable<any> {
    return this.http.get('the/url', {responseType: 'text'});
}

And this is what it looks like when i do the call in my component:

this.myService.getReceipt().subscribe(data => {
    console.log('receipt data');
    console.log(data);
});

So everything is working, but I can't figure out how to do the next step which is actually making the pdf download. Note: the "receipt data" that i log in the console looks like this:

%PDF-1.3
%����
1 0 obj
<</Author <> /Creator (cairo 1.14.6 (http://cairographics.org))
  /Keywords <> /Producer (WeasyPrint 0.42 \(http://weasyprint.org/\))
  /Title (Receipt)>>
endobj...

I don't know what format this is, but I'm guessing that this is raw pdf data in it's native format. How can i force this to data to download?

Note also, I have searched many posts on SO and tried a few things. The following is something I tried that almost worked:

var link = document.createElement('a');
link.href = 'the/url';
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));

What this did was force a download, however because the token was not properly in the header all I got was a message from the backend saying "Invalid Token" instead of my actual pdf.

Any ideas?

you are using incorrect responseType to return PDF documents. It should be responseType: 'blob' in your case . So your http call should look like below -

getReceipt(): Observable<any> {
    return this.http.get('the/url', {responseType: 'blob'});
}

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