Blog Post

Open a PDF in React on the web with react-pdf

Jonathan D. Rhyne
Illustration: Open a PDF in React on the web with react-pdf

In previous articles, you learned about options for opening a PDF in your web app without JavaScript and how to render PDF files in the browser with PDF.js.

Today, you’ll take a step further and explore how to open a PDF in a React application on the web using Vite. Vite is a fast and lightweight development server and build tool that’s perfect for modern web applications. React is a popular JavaScript library for building user interfaces across multiple platforms, including web, iOS, and Android.

In this article, you’ll use react-pdf to render a PDF inside a React app created with Vite. If you’re looking for a React Native guide, check out our blog post on how to open a PDF in React Native.

Getting started

For this article, you’ll be using a library by Wojciech Maj called react-pdf. If you use your favorite online search engine, you’ll likely find another library with the same name, created by Diego Muracciole. However, at the time of writing, the latter is only used to create PDFs.

react-pdf provides a React-based component API for opening PDF files and rendering them using PDF.js.

To get started, create a new React app using Vite. Run the following commands in your terminal:

npm create vite@latest pdf-app -- --template react
cd pdf-app
npm install
npm run dev

After running these commands, Vite will start a development server, and your browser will open with a running React app.

Rendering a PDF in React

To start rendering your first PDF, place the file you want to render inside the ./public directory of the pdf-app folder. This ensures you can access the file from the web.

Next, add react-pdf to your project:

npm install react-pdf

react-pdf comes with two components that are of interest when rendering a PDF: Document and Page. Document is used to open a PDF and is a mandatory part. Within the document, you can mount pages, which are used to render the PDF page. To integrate this into your example project, open ./src/App.js and replace its contents with the following:

import { useState } from 'react';
import { Document, Page } from 'react-pdf';

const App = () => {
	const [numPages, setNumPages] = useState(null);
	const [pageNumber, setPageNumber] = useState(1);

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

	const goToPrevPage = () => setPageNumber((prevPage) => prevPage - 1);
	const goToNextPage = () => setPageNumber((prevPage) => prevPage + 1);

	return (
		<div>
			<nav>
				<button onClick={goToPrevPage}>Prev</button>
				<button onClick={goToNextPage}>Next</button>
			</nav>

			<div style={{ width: 600 }}>
				<Document
					file="/example.pdf"
					onLoadSuccess={onDocumentLoadSuccess}
				>
					<Page pageNumber={pageNumber} width={600} />
				</Document>
			</div>

			<p>
				Page {pageNumber} of {numPages}
			</p>
		</div>
	);
};

export default App;

This is already enough to render a PDF in React.

Place your PDF file in the ./public directory and name it example.pdf. If you don’t have a PDF file handy, you can use this example PDF.

Since react-pdf doesn’t come with a user interface, you’ve built your own. In the example above, you render two buttons to navigate the page within the <nav> elements and show the total progress on the bottom. The result looks something like what’s shown below.

Enabling advanced PDF features in react-pdf

By default, react-pdf enables important features of PDF.js — including the text layer, which allows you to copy and paste text from a PDF. However, one feature that’s disabled is the dedicated annotation layer. In a PDF, annotations provide additional information and enable the use of hyperlinks. In the example PDF, there’s a hyperlink on the first page that you want to enable as well. To do this, import an additional file for the CSS that’s needed:

import 'react-pdf/dist/Page/AnnotationLayer.css';
Screenshot of a PDF page with a link annotation

Another improvement you can make is to use web workers so that your PDFs can be rendered in another thread. This keeps the main window responsive at all times. Luckily, react-pdf comes with prebuilt support for adding this option to webpack, and Create React App uses webpack under the hood.

To enable web workers, replace your input line with the following:

import React, { Component } from "react";
- import { Document, Page } from "react-pdf";
+ import { Document, Page } from "react-pdf/dist/entry.webpack";
import "react-pdf/dist/Page/AnnotationLayer.css";

You can see the worker in action by inspecting the page with your favorite developer tools.

Screenshot of Chrome DevTools showing the web worker in action

Conclusion

With just a few lines of code, you were able to utilize the full power of PDF.js in a React application. This is a great and low-cost way to get started with simple use cases. For more complex use cases, a commercial React PDF library can provide additional benefits:

  1. An out-of-the-box PDF viewer user interface (UI) to help speed up development time. Quickly deploy a polished UI in your application and use well-documented APIs to customize the design and layout.

  2. Embed prebuilt PDF tools to easily add functionality like annotating documents, editing PDFs, adding digital signatures to a PDF form, and much more.

  3. View multiple file types — from image files (JPG, PNG, TIFF) to MS Office documents.

  4. Get a quick response from a dedicated support team if you encounter a challenge or issue when integrating the viewer.

At Nutrient, we offer a commercial, feature-rich, and completely customizable JavaScript PDF library that’s easy to integrate and comes with well-documented APIs to handle advanced use cases. Try it for free, and visit our demo to see it in action, or check out our example application to learn more.

FAQ

Here are a few frequently asked questions about opening PDFs in React.

How do I render a PDF in a React app?

You can render a PDF in a React app using the react-pdf library, which provides components like Document and Page to display PDFs.

Where should I place the PDF file in my React app?

Place your PDF file in the public directory to ensure it’s accessible via a URL within your React app.

Can I enable advanced features like annotations in react-pdf?

Yes, you can enable annotations by importing the required CSS: import 'react-pdf/dist/Page/AnnotationLayer.css';.

How can I improve performance when rendering large PDFs?

To improve performance, you can enable web workers, which offload PDF rendering to a background thread.

Author
Jonathan D. Rhyne Co-Founder and CEO

Jonathan joined PSPDFKit in 2014. As CEO, Jonathan defines the company’s vision and strategic goals, bolsters the team culture, and steers product direction. When he’s not working, he enjoys being a dad, photography, and soccer.

Explore related topics

Share post
Free trial Ready to get started?
Free trial