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 '@react-pdf-viewer/core';
<Worker workerUrl="https://unpkg.com/pdfjs-dist@3.4.120/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 v3.4.120. Otherwise, you will see the error message like this:
The API version "3.4.120" does not match the Worker version "2.6.347"
Or
Uncaught Error: Unknown action from worker: undefined
at Worker.MessageHandler._onComObjOnMessage (pdf.js:6846)
However, if you use the Webpack bundler, setting the same version for both worker and the `pdfjs-dist` package can be automated. There are two ways to archive that:
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@3.4.120/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 '@react-pdf-viewer/core';
// Import the styles
import '@react-pdf-viewer/core/lib/styles/index.css';
// Your render function
<Viewer fileUrl="/path/to/document.pdf" />;
The `fileUrl` accepts various sources of documents, including a base 64 string, an array of bytes, or a URL. It's possible to view a document from a remote server as long as the server allows us to access the document.
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={{
border: '1px solid rgba(0, 0, 0, 0.3)',
height: '750px',
}}
>
<Viewer fileUrl="/assets/pdf-open-parameters.pdf" />
</div>
Here is how it looks like:
Congratulation! Now you know how to use the main viewer component to display a PDF document.
By default, the `Viewer` component does not come with other parts such as toolbar and sidebar. If you want to have a full features viewer, please use the default-layout plugin.