Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pdf file not opening in browser

I am receiving a pdf file as api call response from a node.js backend.The file opens in browser window in an encoded format.I have tried to download but the downloaded file has error opening it (error: failed to load pdf document).I am told the response body is base64 encoded.

Is their any way the pdf can be open /downloaded correctly.I am using react.js and is new to it.

code snippet :

import FileDownload from 'js-file-download';

export function getTaxInvoice({token}){
  const authString = `Bearer ${token}`;

  return (dispatch) => {
    return axios.get(`${MAIN_URL}/rental_invoice`,{
      headers: {Authorization: authString, 'Accept': 'application/json','Content-Type': 'application/pdf'},
      responseType: "arraybuffer",//I have tried with blob as well
      encoding: null
      })
    .then((response)=>{
      FileDownload(response, 'some.pdf');
      const taxInvoiceUrl = window.URL.createObjectURL(new Blob([response.data]));
      window.open(taxInvoiceUrl, "_blank");
      console.log( response); 
      // dispatch(taxInvoiceLoadSuccess(taxInvoiceUrl));
      // dispatch(onViewChanged("rental_invoice"));
    }) 
    .catch((error)=>{
      dispatch(taxInvoiceLoadFailed());
    })
  }
}

response from api call:image snippet

like image 977
Rem Avatar asked Dec 07 '25 03:12

Rem


1 Answers

Here is an example of some code I have used in the past to do this:

function downloadURI (url, name) {
  var link = document.createElement('a')
  link.download = name
  link.href = url
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

export function download (url, type = 'application/pdf', name = 'example') {
  get(url, (err, result) => {
    if (err) return handleError(err)
    const blob = new Blob([result.body], { type })
    const downloadUrl = URL.createObjectURL(blob)
    downloadURI(downloadUrl, name)
  })
}

It will download the file and create an object url and automatically trigger opening the file by programatically clicking a link.

like image 146
justin.m.chase Avatar answered Dec 08 '25 17:12

justin.m.chase