DEV Community

Mohit Kumar Yadav
Mohit Kumar Yadav

Posted on

Display online/offline pdf files in React using react-pdf

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`
Enter fullscreen mode Exit fullscreen mode
  • Use
<Document
  file={{ url: urlPdf }}
  onLoadSuccess={onDocumentLoadSuccess}
>
  // pages here, we will get back to that later
</Document>
Enter fullscreen mode Exit fullscreen mode

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}` }}
Enter fullscreen mode Exit fullscreen mode
  • 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>
Enter fullscreen mode Exit fullscreen mode
  • 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

Top comments (0)