React PDF viewer
v1.4.0

Basic usage

Setting up the worker

pdfjs uses a web worker to process the most tasks which take time such as parsing and rendering a PDF document. The web worker is loaded via the workerUrl parameter:

import { Worker } from '@phuocng/react-pdf-viewer';

<Worker workerUrl="https://unpkg.com/pdfjs-dist@2.2.228/build/pdf.worker.min.js">
    <!-- The viewer component will be put here -->
    ...
</Worker>

It's up to you to use the pdf.worker.min.js file from popular services, such as

or download and store it on your server.

Note

It's very important to note that the worker version and the pdfjs package (mentioned in the Install pdfjs library section of Getting started) have to be the same.

This guide uses the pdfjs v2.2.228. Otherwise, you will see the error message like this:

The API version "2.2.228" does not match the Worker version "2.1.266".

If you use the viewer component in different pages, it's recommended to place the Worker at the layout level.

For example, in a typical React application, we often render the App component at a root element as following:

render(<App />, document.getElementById('root'));

In this case, we should use the Worker component inside the App component:

const App = () => {
    return (
        <Worker
            workerUrl="https://unpkg.com/pdfjs-dist@2.2.228/build/pdf.worker.min.js"
        >
            ...
        </Worker>
    );
};

Using the viewer component

When the worker is ready, it's time to use the viewer component. To display a PDF document, you have to pass its URL to the viewer's fileUrl parameter:

// Import the main component
import Viewer from '@phuocng/react-pdf-viewer';

// Import the CSS
import '@phuocng/react-pdf-viewer/cjs/react-pdf-viewer.css';

<Viewer fileUrl="/path/to/document.pdf" />

By default, the viewer will take the full size of its container. Hence you have to indicate the height of element that you would like to display the document:

<div
    style={{
        height: '750px',
    }}
>
    <Viewer fileUrl="/assets/pdf-open-parameters.pdf" />
</div>

Here is how it looks like:

/ 8
90%

Congratulation! Now you know how to use the main component to display a PDF document.