Reputation: 5790
I'm trying to render a PDF in an Angular 5 app.
Basically I'm sending a GET-request in order to get the file stream (no link! That's not possible in our scenario by compliance). The file stream comes with Content-Type: application/pdf
.
Now I have 2 problems:
First of all the response comes back from the server with 200 (which is OK, but it always reports an error in my angular app:
The method for fetching the PDF looks like this:
fetchPdfAjaxRequest(caseId: string) {
this.caseListService.getPdfFileStream(caseId)
.takeUntil(this.ngUnsubscribe)
.subscribe( (res) => {
console.log(res);
},
(error) => {
this.errorService.displayError(error.status, error.statusText);
});
}
My service method looks like this:
public getPdfFileStream(caseId: string) {
const url = this.CASE_API_URL + '/' + caseId + '/pdf';
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
return this.httpClient.get(url, {headers: headers});
}
However, even though it responds with a 200, it goes in the error branch. Is it maybe because I need to set some additional headers in the request?
The response body is just a huge string:
// just an excerpt from the "response" tab in Chrome dev tools
JVBERi0xLjQKMSAwIG9iago8PAovVGl0bGUgKP7/KQovQ3JlYXRvciAo/v8AdwB
Now I need to parse that string and render it as a PDF.
Does anyone have a clue... - why the response shows a 200 from the server, but goes in the error branch in Angular? - how I can render that huge string (blob) to a PDF? I though of this lib ( https://vadimdez.github.io/ng2-pdf-viewer/). As an src attribute it can take a URL, or a Uint8Array (which might be something like the string?)
Any help is greatly appreciated :)
@UPDATE:
The solution for the first problem (not getting the file stream) has been answered by @Zlatko.
Now, for how to render the PDF I found another post and came to the following solution:
let file = new Blob([pdf], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
Upvotes: 5
Views: 8982
Reputation: 19588
The default responseType for HttpClient is 'json'. Tell angular to expect a binary:
return this.httpClient.get(url, { headers: headers, responseType: 'blob' });
Take a look at HttpClient docs.
Upvotes: 6