Home
About
Contacts

Displaying PDFs in a React Application: A Step-by-Step Guide

Displaying PDFs in a React application is a frequent necessity for modern frontend development. Whether you’re showcasing documents, reports, or any other form of textual information, integrating PDF display functionality enhances user experience. In this guide, we’ll explore two methods to seamlessly incorporate PDF viewing capabilities into your React applications.

Method 1: Embed or Iframe

The simplest method to display a PDF in a React application is by using the <embed> or <iframe> HTML elements to render the PDF from an external source. This approach has both advantages and limitations.

Using embed

<embed 
  src="example.com/sample.pdf" 
  type="application/pdf" 
  width="100%" 
  height="100%" 
/>

Using iframe

<iframe src="example.com/sample.pdf" width="100%" height="100%">

Pros:

  1. Pre-configured toolbar: The default toolbar provided by the browser for PDF viewing is automatically available, saving development time and effort.
  2. Resource efficiency: Rendering PDFs using <embed> or <iframe> typically consumes fewer resources compared to other methods, leading to smoother performance.

Cons:

  1. Limited configurability: Customizing the appearance and functionality of the PDF viewer is restricted with this method. Developers have minimal control over styling and feature enhancements.

Method 2: react-pdf

Utilizing the React PDF Library For more extensive control and customization options, developers can opt for utilizing the React PDF library. This method offers greater flexibility and enables developers to create tailored PDF viewing experiences within their React applications.

To get started with the React PDF library, follow these steps:

Step 1: Install the library using npm:

npm install react-pdf

Step 2: Develop a dedicated component to render PDFs within your React application

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

interface IProps {
  pdfUrl: string;
}

const Pdf = ({ pdfUrl }: IProps): JSX.Element => {
  pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;

  const [numOfPages, setNumOfPages] = useState<number>(0);

  const onLoadSuccess = ({ numPages }: { numPages: number }): void => setNumOfPages(numPages);

  return (
    <Document file={pdfUrl} onLoadSuccess={onLoadSuccess}>
      {Array(numOfPages)
        .fill(null)
        .map((_, index) => (
          <Page key={index} pageNumber={index + 1} />
        ))}
    </Document>
  );
};

export default Pdf;
  1. Imports:
    • React is imported to enable the use of JSX syntax.
    • useState is imported from React to manage state within the component.
    • pdfjs, Document, and Page are imported from the react-pdf library. pdfjs is used to configure global options for PDF rendering, while Document and Page are components provided by react-pdf for rendering PDF documents.
    • Two CSS files related to PDF rendering are imported: "react-pdf/dist/Page/AnnotationLayer.css" and "react-pdf/dist/Page/TextLayer.css".
    • An additional CSS file, "./Pdf.scss", is imported, which presumably contains styles specific to this component.
  2. Interface:
    • An interface IProps is defined, specifying the type of props that the component expects. In this case, it expects a prop named pdfUrl of type string.
  3. Component Definition:
    • The Pdf component is defined as a functional component that takes props as input.
    • Within the component body, pdfjs.GlobalWorkerOptions.workerSrc is set to specify the location of the PDF.js worker script. This script is necessary for rendering PDF documents and is provided by the pdfjs library.
    • State is initialized using the useState hook. numOfPages state variable is used to keep track of the total number of pages in the PDF document.
    • The onLoadSuccess function is defined to handle the onLoadSuccess event emitted by the Document component. When the PDF document is successfully loaded, this function updates the numOfPages state with the total number of pages in the document.
    • The component returns a Document component from react-pdf with the file prop set to the value of pdfUrl. This component is responsible for loading and rendering the PDF document.
    • Inside the Document component, an array of Page components is rendered. The Array(numOfPages).fill(null).map expression generates an array with numOfPages elements, each representing a page of the PDF document. For each page, a Page component is rendered with the pageNumber prop set to the page index plus one.
  4. Export:
    • The Pdf component is exported as the default export of the module, making it available for use in other parts of the application.

Pros:

  1. Extended configurability: The React PDF library offers a plethora of customization options, allowing developers to tailor the PDF viewer to specific requirements.
  2. Enhanced functionality: With the ability to customize various aspects of the PDF viewer, developers can enrich the user experience by adding interactive elements and features.

Cons:

  1. Increased resource usage: Compared to the <embed> or <iframe> approach, utilizing the React PDF library may require additional resources for rendering PDFs within the application.
  2. Larger package size: Incorporating the React PDF library may contribute to an increase in the application’s overall package size, potentially impacting performance and load times.

Conclusion: Incorporating PDF display functionality into React applications is crucial for various use cases. While the <embed> or <iframe> method offers simplicity and efficiency, the React PDF library provides unparalleled configurability and functionality. By carefully considering the project requirements and trade-offs associated with each method, developers can effectively integrate PDF viewing capabilities into their React applications, thereby enhancing user experience and overall application functionality.

Related posts