Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get PDF through API in angular service

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.

like image 380
Curtis Avatar asked May 14 '18 14:05

Curtis


1 Answers

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!


UPDATE - ANGULAR7 & FILESAVER V.^2.0.1+


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!

like image 150
Deadpool Avatar answered Oct 15 '22 17:10

Deadpool