Mohit Kumar Yadav
Posted on September 6, 2020
react-pdf is a great package for react it's based on the pdf.js from Mozilla.
- Install
npm i react-pdf
- Import
import { Document, Page, pdfjs } from 'react-pdf'
// right after your imports
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`
- Use
<Document
file={{ url: urlPdf }}
onLoadSuccess={onDocumentLoadSuccess}
>
// pages here, we will get back to that later
</Document>
in above code urlPDF is url to pdf. Remember this resource must not be blocked by CORS. Or pdf will not render.
If the resources is not available for cross origins use this instead (just a temporary solution, don't use it in production).
file={{ url: `https://cors-anywhere.herokuapp.com/${urlPdf}` }}
- onLoadSuccess is invoked when the file has loaded use this to set total pages in pdf const [totalPages, setTotalPages] = useState(null) const onDocumentLoadSuccess = ({ numPages }) => setTotalPages(numPages)
- Now we have totalPages, let's display the pages now
<Document
file={{ url: attachment.url }}
onLoadSuccess={onDocumentLoadSuccess}
>
{
Array.apply(null, Array(totalPages))
.map((x, i) => i + 1)
.map((page) => <Page pageNumber={page} />)
}
</Document>
- Turn off IDM extension module in your browser or it will prompt to download the file and you'll see and error "faild to load" in the browser.
- References https://github.com/wojtekmaj/react-pdf
💖 💪 🙅 🚩
Mohit Kumar Yadav
Posted on September 6, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.