How to display PDF in React?

Sometimes, we want to display PDF in React.

In this article, we’ll look at how to display PDF in React.

How to display PDF in React?

To display PDF in React, we can use the react-pdf library.

To add it, we run:

npm i react-pdf

Then we can use it by writing:

import React, { useState } from "react";
import { Document, Page, pdfjs } from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.js`;

export default function App() {
  const [numPages, setNumPages] = useState(null);
  const [pageNumber] = useState(1);

  const onDocumentLoadSuccess = ({ numPages }) => {
    setNumPages(numPages);
  };

  return (
    <div>
      <Document
        file="https://www.jianjunchen.com/papers/CORS-USESEC18.slides.pdf"
        onLoadSuccess={onDocumentLoadSuccess}
      >
        <Page pageNumber={pageNumber} />
      </Document>
      <p>
        Page {pageNumber} of {numPages}
      </p>
    </div>
  );
}

We set the pdfjs.GlobalWorkerOptions.workerSrc to the URL of the pdf.js worker used to load the PDF.

Then we use the Document component with the file prop set the URL of the PDF.

The onLoadSuccess prop is set to the onDocumentLoadSuccess function which takes an object with the numPage property so we know how many pages the loaded PDF has.

Then we can use the Page component to load the pages.

We should see the PDF’s first page displayed if we load the PDF from our own domain or from a server that has CORS enabled.

Conclusion

To display PDF in React, we can use the react-pdf library.