How to Build a React.js PDF Viewer with react-pdf | PSPDFKit (2024)

How to Build a React.js PDF Viewer with react-pdf | PSPDFKit (1)

This article was first published in September 2021 and was updated in August 2024.

In this blog post, you’ll learn how to build a React.js PDF viewer using the react-pdf library. react-pdf is a widely used open source library designed specifically for rendering PDF files in React applications. This library leverages the power of PDF.js, a popular open source project by Mozilla, to parse and render PDF documents in the browser.

In the first part of this blog post, you’ll look at how to create the PDF viewer with react-pdf, and in the second part, you’ll be able to follow along with a guide on how to integrate the PSPDFKit React.js PDF viewer library into a React.js project.

Open Source React.js PDF Viewer Libraries

There are a couple of open source React PDF viewer libraries. One of the most popular is the @react-pdf/renderer library, with 510K weekly downloads on npm. It’s used for creating PDF files in the browser, on the server, or on mobile devices. If you want to work with this library, please refer to our How to Create a PDF with React.js blog post.

Another popular library is react-pdf by Wojciech Maj, with around 950K weekly downloads on npm. It’s used to display existing PDFs. This library will be used in this blog for the purpose of creating a PDF viewer.

Why Choose react-pdf?

react-pdf is an excellent choice for developers looking to integrate PDF viewing functionality into their React applications. Here are some key benefits:

  • Ease of Integrationreact-pdf provides a straightforward API, making it easy to integrate into existing React projects. You can quickly display PDFs with minimal setup.

  • Flexibility — The library offers components like Document and Page, allowing developers to build custom PDF viewers tailored to specific needs. Whether you want a simple viewer or a more feature-rich interface, react-pdf gives you the tools to create it.

  • Customization — While react-pdf doesn’t come with a built-in user interface, this is actually a strength. It allows you to create a UI that perfectly fits your application’s design and user experience. You can add navigation controls, zoom functionality, and more, all using standard React components.

  • Compatibility — As a pure React library, react-pdf is fully compatible with React’s ecosystem. Whether you’re working with hooks, context, or other React features, react-pdf integrates seamlessly.

  • Community Support — With around 950K weekly downloads on npm, react-pdf has a large and active community. This means you can find plenty of resources, examples, and support from other developers who are using the library.

Requirements to Get Started

To get started, you’ll need:

  • Node.js version 14 or later.

  • A package manager compatible with npm. This guide contains usage examples for Yarn and the npm client (installed with Node.js by default). Make sure the npm version is 5.6 or greater.

Building a React.js PDF Viewer with react-pdf

Start by creating a React.js project with vite:

npm create vite@latest react-pdf-demo -- --template react

After the project is created, change the directory into the project folder:

cd react-pdf-demo

Adding react-pdf

  1. Now, you can install the npm package for the react-pdf library from the terminal:

npm install react-pdf
  1. Place the file you want to render inside the public directory of the react-pdf-example project. You can use our demo document as an example; you just need to rename it to document.pdf.

Displaying a PDF

  1. react-pdf comes with two components: Document and Page. Document is used to open a PDF and is mandatory. 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.jsx and replace its contents with the following:

import { useState } from 'react';import { Document, Page } from 'react-pdf';// Text layer for React-PDF.import 'react-pdf/dist/Page/TextLayer.css';const App = () => {const [numPages, setNumPages] = useState(null);const [pageNumber, setPageNumber] = useState(1);const onDocumentLoadSuccess = ({ numPages }) => {setNumPages(numPages);};const goToPrevPage = () =>setPageNumber(pageNumber - 1 <= 1 ? 1 : pageNumber - 1);const goToNextPage = () =>setPageNumber(pageNumber + 1 >= numPages ? numPages : pageNumber + 1,);return (<div><nav><button onClick={goToPrevPage}>Prev</button><button onClick={goToNextPage}>Next</button><p>Page {pageNumber} of {numPages}</p></nav><Documentfile="pspdfkit-web-demo.pdf"onLoadSuccess={onDocumentLoadSuccess}><Page pageNumber={pageNumber} /></Document></div>);};export default App;

For react-pdf to work, a PDF.js worker needs to be provided. You can do this in a couple of ways. For most cases, importing the worker will work as was done in the src/App.jsx file:

import { pdfjs } from 'react-pdf';pdfjs.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs',import.meta.url,).toString();// Rest of code.

You can read more about how to configure a PDF.js worker in your project here.

  1. Now, start the application by running the following:

npm run dev

One of the disadvantages of using react-pdf is that it doesn’t come with a UI. In this example, you’ve rendered two buttons to navigate between pages and showed the total number of pages.

How to Build a React.js PDF Viewer with react-pdf | PSPDFKit (2)

You can access the full code on GitHub.

Limitations of react-pdf

Overall, react-pdf is a great open source project, but it has some disadvantages:

  • It doesn’t come with a user interface out of the box. If you need a UI to help users navigate through a PDF, you’ll need to build it from scratch.
  • Text selection doesn’t work properly. If you try to select text in a PDF, you’ll see that it’s not a good user experience.
  • Rendering large PDF files or documents with many pages can sometimes impact performance, particularly in resource-constrained environments.

Building a React.js PDF Viewer with PSPDFKit

We offer a commercial React.js PDF library that can easily be integrated into your web application. It comes with 30+ features that let you view, annotate, edit, and sign documents directly in your browser. Out of the box, it has a polished and flexible UI that you can extend or simplify based on your unique use case.

  • A prebuilt and polished UI
  • 15+ annotation tools
  • Support for multiple file types
  • Dedicated support from engineers

Creating a New React Project

  1. Use vite to scaffold out a simple React application:

npm create vite@latest pspdfkit-react-example -- --template react
  1. Change to the created project directory:

cd pspdfkit-react-example

Adding PSPDFKit to Your Project

  1. Now, add PSPDFKit for Web as a dependency:

npm install pspdfkit
  1. As you’re using the WebAssembly build of PSPDFKit for Web, the final setup step is to copy files the browser will need from the npm module:

cp -R ./node_modules/pspdfkit/dist/pspdfkit-lib public/pspdfkit-lib

The code above will copy the pspdfkit-lib directory from within node_modules/ into the public/ directory to make it available to the SDK at runtime.

  1. Make sure your public directory contains a pspdfkit-lib directory with the PSPDFKit library assets.

Displaying a PDF

  1. Add the PDF document you want to display to the public directory. You can use our demo document as an example.

  2. Add a component wrapper for the PSPDFKit library and save it as src/components/ViewerComponent.jsx:

import { useEffect, useRef } from 'react';export default function ViewerComponent(props) {const containerRef = useRef(null);useEffect(() => {const container = containerRef.current;let PSPDFKit;(async function () {PSPDFKit = await import('pspdfkit');PSPDFKit.unload(container);await PSPDFKit.load({// Container where PSPDFKit should be mounted.container,// Use dark theme.theme: PSPDFKit.Theme.DARK,// The document to open.document: props.document,// Use the public directory URL as a base URL. PSPDFKit will download its library assets from here.baseUrl: `${window.location.protocol}//${window.location.host}/${import.meta.env.BASE_URL}`,});})();return () => PSPDFKit && PSPDFKit.unload(container);}, [props.document]);return (<divref={containerRef}style={{ width: '100%', height: '100vh' }}/>);}

To load PSPDFKit for Web into the ViewerComponent, use PSPDFKit.load when the component has mounted.

  1. Now, all that’s left is to render the ViewerComponent in App.jsx by loading the PDF you downloaded earlier:

import ViewerComponent from './components/ViewerComponent';function App() {return (<div className="App" style={{ width: '100vw' }}><div className="App-viewer"><ViewerComponent document={'document.pdf'} /></div></div>);}export default App;
  1. You can also open a different PDF file by adding a button and adding a handler to the onClick event:

// App.jsximport { useState } from 'react';import ViewerComponent from './components/ViewerComponent';function App() {const [document, setDocument] = useState('document.pdf');const handleOpen = () => setDocument('another-example.pdf');return (<div className="App" style={{ width: '100vw' }}><button className="App-button" onClick={handleOpen}>Open another document</button><div className="App-viewer"><ViewerComponent document={document} /></div></div>);}export default App;

You can use this example document as a second example. Rename it to another-example.pdf, and then add it to the /public folder.

When you click Open another document, it loads the another-example.pdf file.

  1. Your project structure will now look like this:

pspdfkit-react-example├── public│ ├── pspdfkit-lib│ └── document.pdf│ └── another-example.pdf├── src│ ├── components│ | └── ViewerComponent.jsx| └── App.js└── package.json
  1. Start the app and run it in your default browser:

npm run dev

You’ll now see your PDF rendered in the container element. Try using the toolbar to navigate through, annotate, and search in the document. Note that because PSPDFKit is a commercial product, you’ll see a PSPDFKit for Web Evaluation notice on the document. To get a license key, contact Sales.

How to Build a React.js PDF Viewer with react-pdf | PSPDFKit (3)

You can find the finished code on GitHub.

If you hit any snags, don’t hesitate to reach out to our Support team for help.

Adding Even More Capabilities

Once you’ve deployed your viewer, you can start customizing it to meet your specific requirements or easily add more capabilities. To help you get started, here are some of our most popular React.js guides:

  • Adding annotations
  • Editing documents
  • Filling PDF forms
  • Adding signatures to documents
  • Real-time collaboration
  • Redaction
  • UI customization

Conclusion

In this post, you first saw how to build a React.js PDF viewer with the react-pdf library. In the second half, you walked through how to deploy the PSPDFKit React.js PDF viewer.

You can also deploy our vanilla JavaScript PDF viewer or use one of our many web framework deployment options like Vue.js, Angular, and jQuery. To see a list of all web frameworks, start your free trial. Or, launch our demo to see our viewer in action.

FAQ

Here are a few frequently asked questions about building a PDF viewer in React.js.

How Can I Create a PDF Viewer in React.js Using react-pdf?

You can create a PDF viewer in React.js by installing the react-pdf library, importing the necessary components, and using the Document and Page components to render PDF files.

What Are the Main Components of the react-pdf Library?

The main components are Document for loading and Page for rendering individual pages of a PDF. These components utilize PDF.js to display PDF content.

How Do I Install and Set Up react-pdf in a React Project?

Install react-pdf using npm with npm install react-pdf and include it in your project by importing the necessary components. Then, configure the PDF.js worker and set up the components to display your PDF.

What Are the Limitations of the react-pdf Library?

react-pdf does not come with a built-in user interface, and text selection can be problematic. Users need to build navigation controls and other UI elements from scratch.

How Can I Enhance the Functionality of a React.js PDF Viewer?

You can enhance functionality by integrating additional libraries like PSPDFKit, which offers more features like annotations, form filling, and advanced UI components.

Author

How to Build a React.js PDF Viewer with react-pdf | PSPDFKit (4)

Hulya MasharipovTechnical Writer

Hulya is a frontend web developer and technical writer at PSPDFKit who enjoys creating responsive, scalable, and maintainable web experiences. She’s passionate about open source, web accessibility, cybersecurity privacy, and blockchain.

How to Build a React.js PDF Viewer with react-pdf | PSPDFKit (5)

How to Build a React.js PDF Viewer with react-pdf | PSPDFKit (2024)
Top Articles
Things that can decrease life expectancy
How Google Pay helps keep your data private - Android
Christian McCaffrey loses fumble to open Super Bowl LVIII
Skyward Sinton
AllHere, praised for creating LAUSD’s $6M AI chatbot, files for bankruptcy
Avonlea Havanese
Access-A-Ride – ACCESS NYC
San Diego Terminal 2 Parking Promo Code
Klustron 9
Holly Ranch Aussie Farm
Mohawkind Docagent
Athletic Squad With Poles Crossword
Sunday World Northern Ireland
Catsweb Tx State
Brutál jó vegán torta! – Kókusz-málna-csoki trió
Wordscape 5832
Persona 4 Golden Taotie Fusion Calculator
Trini Sandwich Crossword Clue
Scholarships | New Mexico State University
A Guide to Common New England Home Styles
Connect U Of M Dearborn
ARK: Survival Evolved Valguero Map Guide: Resource Locations, Bosses, & Dinos
Water Days For Modesto Ca
Mychart Anmed Health Login
Forest Biome
The Blind Showtimes Near Amc Merchants Crossing 16
SN100C, An Australia Trademark of Nihon Superior Co., Ltd.. Application Number: 2480607 :: Trademark Elite Trademarks
Craigslist Rome Ny
Harrison 911 Cad Log
Craig Woolard Net Worth
+18886727547
Dreamcargiveaways
Cheap Motorcycles Craigslist
Staar English 1 April 2022 Answer Key
Gets Less Antsy Crossword Clue
Wattengel Funeral Home Meadow Drive
ENDOCRINOLOGY-PSR in Lewes, DE for Beebe Healthcare
Craigslist Lakeside Az
1Exquisitetaste
No Boundaries Pants For Men
Alpha Labs Male Enhancement – Complete Reviews And Guide
Killer Intelligence Center Download
Menu Forest Lake – The Grillium Restaurant
9294027542
Turok: Dinosaur Hunter
Christie Ileto Wedding
Missed Connections Dayton Ohio
Grand Park Baseball Tournaments
Craigslist Marshfield Mo
Sml Wikia
Where Is Darla-Jean Stanton Now
Hy-Vee, Inc. hiring Market Grille Express Assistant Department Manager in New Hope, MN | LinkedIn
Latest Posts
Article information

Author: Rob Wisoky

Last Updated:

Views: 6662

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Rob Wisoky

Birthday: 1994-09-30

Address: 5789 Michel Vista, West Domenic, OR 80464-9452

Phone: +97313824072371

Job: Education Orchestrator

Hobby: Lockpicking, Crocheting, Baton twirling, Video gaming, Jogging, Whittling, Model building

Introduction: My name is Rob Wisoky, I am a smiling, helpful, encouraging, zealous, energetic, faithful, fantastic person who loves writing and wants to share my knowledge and understanding with you.