Reputation: 533
I managed to generate the pdf document and show it on the page but I am struggling to setup an option to download it.
It is possible to setup something like click here to download the document?
Please refer to the code below:
import React, {Component} from 'react';
import { PDFViewer } from '@react-pdf/renderer';
import FeeAcceptance from '../Pdfgenerator/FeeAcceptance'
class AcceptFees extends Component {
render () {
return (
<>
<PDFViewer>
<FeeAcceptance member_detail={'test'} />
</PDFViewer >
<h1>click<a href="?????"> here </a>to download the document</h1>
</>
);
}
}
export default AcceptFees;
Thank you in advance.
Upvotes: 10
Views: 29605
Reputation: 66
We can also use ReactPDF.pdf
. here's a small code sample of an async function that returns a url
(or even blob
if the case requires !). We can use this url
to download our PDF.
renderUrl = async() => new Promise((resolve, reject) => {
const blob = await ReactPDF.pdf(<FeeAcceptance member_detail={'test'} />).toBlob()
const url = URL.createObjectURL(blob)
if(url && url.length>0){
resolve(url)
}
}
).then(res => res).catch(err => console.log(err))
To Download the generated url
we can use the download
attribute of a
tag. Here's an example
let sampleTab = window.open()
if(sampleTab) {
renderUrl().then(generatedUrl => {
if( generatedUrl ){
let aTag = document.createElement('a')
aTag.href = generatedUrl
aTag.style = "display: none";
aTag.download = 'FeeAcceptance.pdf'
document.body.appendChild(aTag)
aTag.click()
} // else -> means something went wrong during pdf generation
}).catch(err => console.log(err))
} // else -> means new tab can't be opened ... (some Adblock issue)
Upvotes: 4
Reputation: 533
In case you face the same problem, I found something that help. Replace PDFViewer for the code below:
<PDFDownloadLink document={<FeeAcceptance />} fileName="fee_acceptance.pdf">
{({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'Download now!')}
</PDFDownloadLink>
https://react-pdf.org/components
Upvotes: 21