0

I want to download pdf from the api response directly and currently i am using js-file-download package. I am currently getting empty pdf by using this. Below is my code.

const fileDownload = require("js-file-download");
const handleDownloadPdf = async () => {
    console.log(statusData);
    try {
      return api(
        `my_api_url`,
        {},
        "get"
      ).then((apiCall) => {
        console.log(apiCall);
        fileDownload(apiCall.data, "InvoiceSearchExport.pdf");
      });
    } catch (err) {
      console.log({ Error: err });
    }
  };
 <Menu.Item onClick={() => handleDownloadPdf()} key="3">
        Download
 </Menu.Item>

This is what i am geting from my api response inside apiCall.data.

%PDF-1.7 1 0 obj << /Type /Catalog /Outlines 2 0 R /Pages 3 0 R >> endobj 2 0 obj << /Type /Outlines /Count 0 >> endobj 3 0 obj << /Type /Pages /Kids [6 0 R ] /Count 1 /Resources << /ProcSet 4 0 R /Font << /F1 8 0 R /F2 9 0 R

/XObject << /I1 10 0 R /I2 11 0 R

/MediaBox [0.000 0.000 595.280 841.890] endobj 4 0 obj [/PDF /Text /ImageC ] endobj 5 0 obj << /Producer (�� Can someone please help me with this!

deep shah
  • 79
  • 3
  • 9
  • Downloading a pdf in react should be no different from downloading a file in plain javascript. The answer of the following question will help you, I hope. https://stackoverflow.com/questions/34691525/how-to-download-pdf-automatically-using-js – Stratis Dermanoutsos May 03 '22 at 06:45
  • No. actually i want to directly download file on button click via api call. So i dont think so there is a case of same in the above link – deep shah May 03 '22 at 06:53
  • According to the github for js-file-download if you're downloading binary files(unsure if pdf counts as this) you must handle the data as a blob - https://github.com/kennethjiang/js-file-download. – Max Strandberg May 03 '22 at 07:20

1 Answers1

0

Try with this way , maybe will be helpfull

      axios.get("your-api-url/",
        {
            responseType: 'arraybuffer',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/pdf'
            }
        })
        .then((response) => {
            const url = window.URL.createObjectURL(new Blob([response.data]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'file.pdf'); //or any other extension
            document.body.appendChild(link);
            link.click();
        })
        .catch((error) => console.log(error));

If you are using React Router, use this <Link to="/files/file.pdf" target="_blank" download>Download</Link> where /files/file.pdf is inside your public folder.

Read more here - examples

Hakob Sargsyan
  • 1,294
  • 1
  • 9
  • 15