I have a Java based API set up on a server. URL = "ex.com"
It has an endpoint which returns a PDF file. URL = "ex.com/pdf"
It expects a POST request with a parameter specifying which PDF is being requested. params = { location: "report.pdf"}
I would like to be able to use the Angular Http.post observable to get the PDF but it keeps throwing an HttpErrorResponse Http failure during parsing for http://ex.com/pdf
... Unexpected token % in JSON at position 0 at JSON.parse
. But its a PDF I dont want it to be parsed as JSON.
This is my code:
params = {location: "report.pdf"};
return this.http.post<Response>("http://ex.com/pdf", params)
.subscribe(
data => {
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
);
The endpoint works with PostMan. I can use the "Send and Download" option to successfully get the PDF file. So I just need to figure out how to do with in Angular. Appreciate the help.
Try with something like this...
First of all, you will need file-saver node package so run
npm install --save file-saver
.
Then, try with something like this, I copy-paste my code that I used for something similar
public downloadPDF(): any {
var mediaType = 'application/pdf';
this.http.post(this.myUrl, {location: "report.pdf"}, { responseType: 'blob' }).subscribe(
(response) => {
var blob = new Blob([response], { type: mediaType });
saveAs(blob, 'report.pdf');
},
e => { throwError(e); }
);
}
This worked for me, but it was just for saving the file.
Let me know if it works!
I've just migrated my app from Angular v.6 and Filesaver v.<2.0.1 (don't know what version it was but it was a previous one of 2.0.1).
In this new version, you'll have to change the import from:
import { saveAs } from 'file-saver/FileSaver';
to
import { saveAs } from 'file-saver';
Everything else works like previous version!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With