To add a PDF download link using the react-pdf library, you can follow these steps:
-
Install the react-pdf library by running the following npm command:
npm install react-pdf
-
Import the necessary components from the library:
import { Document, Page, pdfjs } from 'react-pdf';
-
Import the PDF file that you want to display and download:
import pdfFile from './path/to/pdfFile.pdf';
-
Declare a state variable to keep track of the number of pages in the PDF:
const [numPages, setNumPages] = useState(null);
-
In your component’s JSX, render the Document component with the PDF file as a prop:
<Document file={pdfFile} onLoadSuccess={({ numPages }) => setNumPages(numPages)} > {/* Render each page of the PDF using the Page component */} {Array.from(new Array(numPages), (el, index) => ( <Page key={index + 1} pageNumber={index + 1} /> ))} </Document>
-
Finally, add a download link by creating an anchor tag () with the “href” attribute set to the URL of the PDF file:
<a href="./path/to/pdfFile.pdf" download>Download PDF</a>