Ankit Singh
Ankit Singh

Reputation: 273

Convert Pdf response from API Call to Blob and generate Blob Url

I am trying to convert the response to blob and then generate url to access that. The response from the get request is Pdf.

Here's what I am doing.

this.$http.get<string>(
        invoicePath
      ).then((response:any)=> {
        console.log("CREATING A BLOB")
        console.log("RESPONSE BLOB: ", response.data); 
        const blob:any = new Blob([response], { type: 'application/pdf; charset=utf-8' });
        console.log("RESPONSE BLOB: ", blob);
        const url= window.URL.createObjectURL(blob);
        // window.open(url);
        return url
        //window.location.href = response.url;
      })

The url returned gives me the below error message. enter image description here

Upvotes: 3

Views: 5560

Answers (1)

Ankit Singh
Ankit Singh

Reputation: 273

We have to convert the response to ArrayBuffer first.

this.$http.get<string>(
        invoicePath, {responseType:'arraybuffer'}
      ).then((response:any)=> {
        console.log("CREATING A BLOB")
        console.log("RESPONSE BLOB: ", response.data); 
        const blob:any = new Blob([response.data], { type: 'application/pdf; charset=utf-8' });
        console.log("RESPONSE BLOB: ", blob);
        const url= window.URL.createObjectURL(blob);
        // window.open(url);
        return url
        //window.location.href = response.url;
      })

Upvotes: 2

Related Questions