Tutorials

How to Build a React.js PDF Viewer with React PDF?

By ComPDFKit | Thu. 07 Dec. 2023
React.js

In this article, we'll focus on the most favored open-source libraries for crafting a PDF Viewer in React.js. Specifically, we're going to guide you through the process of creating a React.js PDF Viewer by leveraging the capabilities of the renowned open-source library — react-pdf

 

Through this walkthrough, you will learn how to implement a fully functional PDF viewer in a React.js application using React-PDF in the first part. In the second part, we will focus on integrating ComPDFKit to provide additional PDF features, further enhancing the document processing experience for users.

How to Build a React.js PDF Viewer with React PDF?

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

 

Open Source React.js PDF Viewer Libraries

 

In React.js development, various open-source libraries, especially react-pdf and @react-pdf/renderer,  which are very popular, facilitate PDF viewing. @react-pdf/renderer with a weekly download count on npm reaching as high as 54K, meanwhile,  the React-PDF weekly download count on npm reaching as high as 1 million. In this blog post, we will focus on building a free PDF viewer using React-PDF.

 

 

 

Build a React.js PDF Viewer with React-PDF

 

Requirements:

 

         - Node.js version 14 or later.

         - A package manager is 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.

 

Create a Project

 

1. Start by creating a React.js project with create-react-app:

npx create-react-app react-pdf-example

 

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

cd react-pdf-example

 

Add react-pdf

 

1. Install and add react PDF library: From the terminal in your React app location, run the following command to pull down all the necessary components.

npm i react-pdf

 

2. Then, follow the code below to create a Webviewer in ”src/components/Webviewer.js”.

import { useState } from "react"
import { Document, Page, pdfjs } from "react-pdf"
import "react-pdf/dist/esm/Page/AnnotationLayer.css"
import 'react-pdf/dist/Page/TextLayer.css';

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

export default function PDFViewer(props) {
  const [numPages, setNumPages] = useState();
  const [pageNumber, setPageNumber] = useState(1);

  function prevPage() {
    setPageNumber(pageNumber - 1 <= 1 ? 1 : pageNumber - 1);
  }

  function nextPage() {
    setPageNumber(pageNumber + 1 >= numPages ? numPages : pageNumber + 1);
  }

  function onLoadSuccess({ numPages }) {
    setNumPages(numPages);
  }

  return (
    <div>
      <nav>
        <button onClick={prevPage}>Previous Page</button>
        <button onClick={nextPage}>Next Page</button>
      </nav>
      <div className="pages">{pageNumber} of {numPages}</div>
      <div className="page">
        <Document
          file='ComPDFKit_Sample_File_Web.pdf'
          onLoadSuccess={onLoadSuccess}
          renderMode="canvas"
        >
          <Page
            key={pageNumber}
            pageNumber={pageNumber}
          />
        </Document>
      </div>
    </div>
  )
}

 

Display a PDF

 

Run the PDF Viewer in your React App in your terminal  by running the following command, the PDF successfully displayed:

npm start

 

 

Limitations of Using React-PDF

 

Despite being a stellar open-source project, React-PDF has its share of limitations:

 

Absence of Built-In User Interface: React-PDF does not come with a pre-configured user interface. If you require an interface to help users navigate through PDF files, you'll need to build it from scratch.

 

Incomplete Text Selection: The text selection functionality in React-PDF is not fully optimized, leading to subpar user experiences when trying to highlight text within PDF documents.

 

Performance Challenges: Rendering large PDF files or multi-page documents can strain React-PDF's performance, especially in environments with limited resources.

 

If you want to integrate more PDF features into your project and improve the user experience, please continue reading our second method: Deploy your PDF viewer using ComPDFKit!

 

 

Build a React.js PDF Viewer with ComPDFKit

 

Additionally, we offer ComPDFKit for Web, which can be easily integrated into your project to increase your proficiency and simplify your workflow by adding any features you want, such as:

 

  • PDF page handling.
  • PDF editing.
  • PDF commenting & replying.
  • Signing PDF documents.
  • Comparing PDF versions.
  • Form filling.
  • Sensitive information redacting.

 

Here, we will provide a detailed guide on how to seamlessly integrate ComPDFKit for Web into your React project, step by step. 

 

Create a New React Project

 

1. Use create-react-app to scaffold out a simple React application:

npx create-react-app compdfkit-react-example

 

2. Change to the created project directory:

cd compdfkit-react-example

 

Add ComPDFKit for Web to Your Project

 

1. Import the “@compdfkit” folder into the root of your project.

 

2. Initialize the ComPDFKit for Web in your project by calling ComPDFKitViewer.init().

 

Display a PDF

 

Pass the PDF address you want to display and your license key into the init function.

import ComPDFKitViewer from "/@compdfkit/webviewer";

export default function Home() {
  let init = false
  const viewer = useRef(null);
  let docViewer = null
  useEffect(() => {
    if (init) return
    init = true

    ComPDFKitViewer.init({
      pdfUrl: 'Your PDF Url',
      license: 'Input your license here'
    }, viewer.current).then((core) => {
      docViewer = core.docViewer
    })
  });

  return (
  )
}

 

The PDF file will be opened and displayed. Also, you can download the React PDF viewer example project by visit ComPDFKit GitHub account to run the Web Demo directly. If you encounter any problems during the process, please contact us immediately!

 

 

Video Guide: Build a React PDF Viewer with ComPDFKit PDF SDK

 

In our latest video tutorial, we offer an in-depth step-by-step guide on how to build a React PDF Viewer by seamlessly integrating the ComPDFKit PDF SDK. Discover the complete process to create a powerful PDF viewing experience in your React applications.

 

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

 

Benefits of Using ComPDFKit

 

Easy Integration: Developers can follow comprehensive documentation of ComPDFKit to easily incorporate this robust SDK into their applications with just a few lines of code.

 

Functional Benefits: Unlike React-PDF, deploying a PDF viewer using ComPDFKit offers unparalleled customization options to meet specific needs. You can enrich your application with additional PDF functionalities such as annotations, document editing, form handling, and digital signatures, significantly enhancing the user experience.

 

Exceptional Support Services: ComPDFKit provides 24/5 online and email support. Whenever you encounter an issue, simply reach out to the online customer service team for a prompt and effective solution.

 

Comprehensive Technical Assistance: Offering unlimited error request support and remote services, ComPDFKit ensures that any development challenges are swiftly addressed, enabling a smooth development process.

 

Pricing Advantage: To facilitate project testing, ComPDFKit offers a 30-day free trial license. Additionally, affordable community licenses are available for individual developers, small to medium-sized businesses, startups, and non-profit organizations, etc.

 

 

Conclusion

 

In this article, you will first learn how to use the open-source React-PDF library to build a PDF viewer. Then, we introduce how to create a feature-rich ComPDFKit React.js PDF viewer.


By deploying the ComPDFKit React.js PDF viewer, you can add a wide array of PDF functionalities to your application, including editing, annotation, form handling, and digital signatures. If you need any assistance during the process, feel free to contact us. ComPDFKit is committed to providing timely support and expert solutions.

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free