0

I am trying to create a button that downloads a PDF in my React component. I have tried several different ways to achieve with no luck. The code below is the closest I've gotten. If I click the button, the pdf downloads but when I open the download it has an error "Failed to load PDF document."

Any ideas how to fix?

  const onButtonDownloadSales = () => {
    fetch('TermsEquipSales.pdf').then(res => {
      res.blob().then(blob => {
        const fileURL = window.URL.createObjectURL(new Blob([blob]));
        let alink = document.createElement('a');
        alink.href = fileURL;
        alink.setAttribute('download', 'TermsEquipSales.pdf')
        document.body.appendChild(alink)
        // alink.download = 'TermsEquipSales.pdf'
        alink.click()
        alink.parentNode.removeChild(alink)
      })
    })
  }


 <Box>
     <button onClick={onButtonDownloadSales}>
       Standard Terms and Conditions for the Sale of Equipment
     </button>
 </Box>
Beth
  • 13
  • 1
  • 5
  • Why are you creating a new blob from an existing blob? Why not just use `createObjectURL(blob)`? – Phil May 30 '23 at 00:42
  • 1
    I doubt very much that `'TermsEquipSales.pdf'` is the correct URL. Where is the file located? Is it bundled with your project and if so, how? – Phil May 30 '23 at 00:44
  • Please try to follow these steps to download the file [Link to the solution](https://stackoverflow.com/a/63965930/15119646) – M.G.S SUPUNTHAKA May 30 '23 at 00:55
  • @M.G.SSUPUNTHAKA OP's code already looks exactly the same – Phil May 30 '23 at 00:58
  • @Phil thank you for looking at my code. I had tried createObjectURL(blob) with the same outcome. I am just desperate lol. My file is located in my src folder, should I move it? – Beth May 30 '23 at 14:15
  • Why bother with `fetch` at all? Just put your file in the `public` folder and use `` – Phil May 30 '23 at 22:43
  • Thanks Phil! I moved my pdf's folder and it's working! Thank you for the realization – Beth May 31 '23 at 19:58

0 Answers0