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>