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:
- Pre-configured toolbar: The default toolbar provided by the browser for PDF viewing is automatically available, saving development time and effort.
- Resource efficiency: Rendering PDFs using <embed> or <iframe> typically consumes fewer resources compared to other methods, leading to smoother performance.
Cons:
- 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;
- Imports:
React
is imported to enable the use of JSX syntax.useState
is imported from React to manage state within the component.pdfjs
,Document
, andPage
are imported from thereact-pdf
library.pdfjs
is used to configure global options for PDF rendering, whileDocument
andPage
are components provided byreact-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.
- Interface:
- An interface
IProps
is defined, specifying the type of props that the component expects. In this case, it expects a prop namedpdfUrl
of type string.
- An interface
- 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 thepdfjs
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 theonLoadSuccess
event emitted by theDocument
component. When the PDF document is successfully loaded, this function updates thenumOfPages
state with the total number of pages in the document. - The component returns a
Document
component fromreact-pdf
with thefile
prop set to the value ofpdfUrl
. This component is responsible for loading and rendering the PDF document. - Inside the
Document
component, an array ofPage
components is rendered. TheArray(numOfPages).fill(null).map
expression generates an array withnumOfPages
elements, each representing a page of the PDF document. For each page, aPage
component is rendered with thepageNumber
prop set to the page index plus one.
- The
- Export:
- The
Pdf
component is exported as the default export of the module, making it available for use in other parts of the application.
- The
Pros:
- Extended configurability: The React PDF library offers a plethora of customization options, allowing developers to tailor the PDF viewer to specific requirements.
- 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:
- 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.
- 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.