Clue Mediator

How to display a PDF in React

📅January 14, 2022

Today we will show you how to display a PDF in React. Here we will use the NPM package to display a PDF as an image in React application. You can also render the PDF via the iFrame element or open it in the new tab and the browser will handle it manually.

Checkout more articles on ReactJS

Demo Application

Output - How to display a PDF in React - Clue Mediator

Output - How to display a PDF in React - Clue Mediator

Steps to display a PDF in React

  1. Install NPM package
  2. Render sample PDF in React component
  3. Output

1. Install NPM package

In this article, we will use the react-pdf to display a PDF. Run the following command to install the package.

npm i react-pdf

2. Render sample PDF in React component

Let’s use the package and create a component to display a PDF.

import React from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import pdf from './sample.pdf';

function App() {

  pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

  // ...
  // ...

  return (
    <document file={pdf} ...="">
    </document>
  );
}

export default App;

As you can see in the above code, we have to follow three steps to render the PDF.

  • Import from the react-pdf.
  • Use `pdf.worker.js` from the external CDN.
  • Render PDF via Document element and page number via Page element.

Let’s combine all things together and see how it works.

App.js

import React, { useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import pdf from './sample.pdf';

function App() {

  pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

  const [totalPages, setTotalPages] = useState(1);
  const [pageNumber, setPageNumber] = useState(1);

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

  const previousPage = () => {
    setPageNumber(prevPageNumber => prevPageNumber - 1);
  }

  const nextPage = () => {
    setPageNumber(prevPageNumber => prevPageNumber + 1);
  }

  return (
    <div class="app">
      <h4>Display a PDF in React - <a href="https://www.cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h4>
      <div>
        <document file={pdf} onloadsuccess={onDocumentLoadSuccess}>
          <page pagenumber={pageNumber}>
        </page></document>
        <p>Page {pageNumber} of {totalPages}</p>
      </div>
      <div>
        <button type="button" disabled <="1}" onclick={previousPage}>
          Previous
        </button>
        <button type="button" disabled>= totalPages}
          onClick={nextPage}>
          Next
        </button>
      </div>
    </div>
  );
}

export default App;

3. Output

Run the application and check the output in the browser.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

Demo & Source Code

GitHub Repository