monica
monica

Reputation: 1484

How to read pdf response in angular 2.0

%PDF-1.7 %���� 4 0 obj <> stream x��Z[o�Fi�F8H�BR@�TJz!��/R��\�n�d�����Jy /��������w����V�x���w�w��;���_���#�S!U:���t|����H�9c���$����@,y�18 �'����q�wr8N��a@�Y8)��I��x4����)�fG_�{2"�䔼�qB����������ŸtSEg��/

I am getting such response from the API. I tried to read it in the calling function, but getting the following error:

error = SyntaxError: Unexpected token % in JSON at position 0 at JSON.parse () at Function.Json.parse

My code is :

downloadInvoice(invoicePdfUrl){
    let invoiceId = invoicePdfUrl.split('/')[2];
    try{
      this.invoiceSub = this.billingService.downloadInvoicePdf(invoiceId).subscribe(
        response => {
          this.downloadFile(response),//console.log(data),
          error => console.log("Error downloading the file."),
            () => console.info("OK");
        },
        error => {
            console.log(error);
        }
      );
    }catch(err){
      this.errorMsg = 'Something went wrong. Try again later.';
      throw err;
    }


downloadFile(data: Response){
    var blob = new Blob([data], { type: 'text/csv' });
    var url= window.URL.createObjectURL(blob);
    window.open(url);
  }

In service :

downloadInvoicePdf(invoiceId){
    let apiUrl = getApiUrl("GET_INVOICE_PDF", [API_PATH.API_VERSION2, invoiceId]); //this method return me the exact url to be hit based on the params
    let headers = new Headers({ 'Accept': 'application/pdf'});
    let options = new RequestOptions({
      headers : headers
    });

    return this.http.get(API_PATH.BASE_ACCOUNTS_ENDPOINT + apiUrl,options).map(res => res.json();
    // return 
  }

Please guide me through the handling of such response.

Upvotes: 0

Views: 3555

Answers (1)

Olaf Horstmann
Olaf Horstmann

Reputation: 16892

First of all: You are missing a closing bracket in .map(res => res.json()>>>)<<<; - maybe this is just a copy/paste-issue.

But now to your actual question: You receive a PDF as response, and you try to parse that PDF-response with a JSON-Parser -> this cannot work, it is like having a text in chinese and expecting someone without the knowledge what chinese characters are to understand that text.

Depending on your use-case, you will need:

  1. A PDF-Parser if you want to extract data
  2. A PDF-Renderer if you want to display the PDF (e.g.: https://mozilla.github.io/pdf.js/)
  3. A File Downloader if you want to download that file to the users local system (e.g.: https://github.com/eligrey/FileSaver.js/) (though there are better ways to do this than with the angular http-client.)

=> For a simple file-download and since you are doing a GET-Request, it'd be the easiest if you just generate the download-url and bind it to an anchor-tag in your template:

<a [attr.href]="pdfDownloadLink">Download me!</a>

Upvotes: 2

Related Questions