Preview PDF files in the browser with React

Last Updated:  February 26, 2020 | Published: February 10, 2019

In addition to my blog post #HOWTO: Up- and downloading files with React and Spring Boot, I want to show you a simple way to display PDF files in the browser with React.

I'm using create-react-app to bootstrap the React application. For styling purposes, I've added semantic-ui-react and semantic-ui-css. The library for previewing the PDF files is called react-pdf:

The library is capable of displaying PDFs from an URL, a local file or from form input. In addition, you can display specific pages of the PDF document and navigate through every page. For a sample setup, I've used the generated <App> component and added the following JSX markup:

The components Document and Page are part of the react-pdf dependency and the rest is part of Semantic UI React. With a file upload, the uploaded file is stored in the state of the <App> component and rendered within the <Document> component. To navigate through the file, I've added a click listener on the wrapper class of the <Document> component and incrementing the current page with every click (or setting to 1 if the end of the document is reached):

To optimize performance and as mentioned in the documentation of the react-pdf getting started guide, you should enable PDF.js worker whenever possible as this will render the PDF file in a separate thread without affecting page performance. The setup for a React project generated with create-react-app is a little bit different then the plain Webpack setup described in the guide. For an up-to-date worker, I've added the following lines to the index.js file:

You can find the whole code base in my GitHub repository and try it out on your machine.

Have fun with previewing PDF files in your browser,

Phil

 

 

 

>