Design Converter
Education
Last updated on Dec 25, 2023
Last updated on Dec 8, 2023
In the modern web development landscape, the ability to display PDF files directly within a web application is a crucial feature. Whether it's for viewing reports, invoices, or e-books, users expect a seamless experience when interacting with PDF documents.
React, a popular library for building user interfaces, offers developers the tools to create rich and interactive UIs. However, when it comes to displaying PDFs, developers often need to rely on additional libraries to bridge the gap between React's capabilities and the specific requirements of rendering PDF files.
PDFs are a standard format for sharing documents that maintain formatting across different platforms and devices, including mobile devices. This consistency ensures all users have the same experience when viewing a document. In a React app, integrating a PDF viewer allows users to access content without downloading and opening the file in a separate application. This integration enhances the user experience by providing immediate access to the content within the same user interface.
The React-PDF library is a popular solution for rendering PDF documents in React applications. It simplifies displaying existing PDFs, much like how images are handled in web pages. With React-PDF, developers can quickly load PDF files and render them within their React components, offering a seamless viewing experience to users.
React-PDF is built on top of PDF.js, a general-purpose PDF rendering library created by Mozilla. This connection ensures that React-PDF benefits from the robustness and browser compatibility of PDF.js.
React-PDF also provides a range of options for customization, allowing developers to tailor the PDF viewer to the needs of their project. Whether it's custom styling, navigation controls, or handling large documents for optimal performance, React-PDF offers the flexibility needed to create a robust PDF viewing experience.
Integrating a PDF viewer into your React app begins with setting up the React-PDF library. This process involves adding the library to your project and importing the necessary components to render PDF documents. React-PDF provides a straightforward approach, ensuring developers can quickly move on to the more exciting aspects of building their application's UI.
Before displaying PDF files in your React app, install the React-PDF library. This famous library is available as an npm package, which means you can add it to your project with a simple npm install command. If you're using yarn, you can equally add the library using the yarn add command. Here's how you can install React-PDF in your project:
npm install react-pdf
Or, if you prefer using yarn:
yarn add react-pdf
With these commands, React-PDF will be added to your project's dependencies, and you'll be ready to import and use its components. It's important to note that React-PDF is frequently updated, so ensure you install the version compatible with your React version to avoid compatibility issues.
Once you have installed the React-PDF library in your project, the next step is to import the necessary components. The primary components provided by React-PDF are Document and Page. The Document component serves as a container for the PDF document, while the Page component is responsible for rendering individual pages within the PDF.
Here's how you can import these components into your React component file:
1import { Document, Page } from 'react-pdf'; 2
After importing, you can use these components in your React app to display PDF documents. The Document component requires a file prop specifying the source of the PDF file you want to display. The source can be a URL, a file imported into your project, or a base64-encoded string.
Once you have React-PDF installed and the components imported into your React project, you're all set to start displaying PDF documents. React-PDF simplifies integrating a PDF viewer into your React app, allowing you to load and render PDF documents quickly.
To load a PDF document using React-PDF, you'll utilize the Document component. This component fetches and parses the PDF data, which can be displayed using the Page component. The file prop on the Document component is versatile, accepting various inputs such as a URL, a file object, or even a binary string.
Here's an example of how to load a PDF document from a URL:
1import React from 'react'; 2import { Document, pdfjs } from 'react-pdf'; 3 4pdfjs.GlobalWorkerOptions.workerSrc = new URL( 5 'pdfjs-dist/build/pdf.worker.min.js', 6 import.meta.url, 7).toString(); 8 9const PdfLoader = ({ fileUrl }) => { 10 return ( 11 <> 12 <Document 13 file={fileUrl} 14 onLoadSuccess={({ numPages }) => console.log(`Document loaded with ${numPages} pages.`)} 15 onLoadError={(error) => console.error('Error occurred while loading document:', error.message)} 16 /> 17 </> 18 19 ); 20}; 21 22export default PdfLoader; 23
In this example, the PdfLoader component accepts a fileUrl prop and passes it to the Document component's file prop. The onLoadSuccess callback is triggered when the document is successfully loaded, providing information such as the total number of pages. The onLoadError callback handles any errors that may occur during the loading process.
After loading the PDF document, you'll want to render the pages within it. The Page component is used for this purpose. Each Page component instance corresponds to a single page in the PDF document, and you can control which page to render using the pageNumber prop.
Here's how you can render the first page of a PDF document:
1import React from 'react'; 2import { Document, Page, pdfjs } from 'react-pdf'; 3 4pdfjs.GlobalWorkerOptions.workerSrc = new URL( 5 'pdfjs-dist/build/pdf.worker.min.js', 6 import.meta.url, 7).toString(); 8 9const PdfViewer = ({ fileUrl }) => { 10 return ( 11 <div> 12 <Document file={fileUrl}> 13 <Page pageNumber={1} /> 14 </Document> 15 </div> 16 ); 17}; 18 19export default PdfViewer; 20
In this PdfViewer component, the Document component loads the PDF document from the provided fileUrl, and the Page component renders the first page of that document. You can render multiple pages by adding more Page components with different pageNumber props.
react-pdf also allows for more advanced page rendering options, such as setting the scale or rotation of pages, customizing the rendering mode, and handling text layers for text selection. These features give you the flexibility to create a PDF viewer tailored to the specific needs of your users and your project.
React-PDF enables you to render PDFs in your React app and offers extensive customization options. This flexibility allows you to tailor the PDF viewer to match your application's look and feel and enhance the user experience with additional functionality like navigation and controls.
The appearance of the PDF viewer can be customized to align with your app's design. React-PDF components accept standard className and style props, allowing you to apply custom styles. You can adjust the size, background color, borders, and more, using either CSS classes or inline styles.
Here's an example of how to apply custom styles to the PDF viewer:
1import React from 'react'; 2import { Document, Page, pdfjs } from 'react-pdf'; 3 4pdfjs.GlobalWorkerOptions.workerSrc = new URL( 5 'pdfjs-dist/build/pdf.worker.min.js', 6 import.meta.url, 7).toString(); 8 9const PdfViewer = ({ fileUrl }) => { 10 11 const customStyles = { 12 border: '6px solid black', 13 borderRadius: '5px', 14 overflow: 'hidden', 15 }; 16 17 return ( 18 <div style={customStyles}> 19 <Document file={fileUrl}> 20 <Page pageNumber={1} /> 21 </Document> 22 </div> 23 ); 24}; 25 26export default PdfViewer; 27
In this PdfViewer component, we've defined a customStyles object with CSS properties and applied it to a wrapper div around the Document component. This approach gives the PDF viewer a custom border and rounded corners.
To enhance the interactivity of your PDF viewer, consider adding navigation controls that allow users to move between pages or zoom in and out of the document. React-PDF does not provide built-in navigation controls, but you can quickly implement your own using React state and event handlers.
Here's an example of adding simple navigation controls to your PDF viewer:
1import React, { useState } from 'react'; 2import { Document, Page, pdfjs } from 'react-pdf'; 3 4pdfjs.GlobalWorkerOptions.workerSrc = new URL( 5 'pdfjs-dist/build/pdf.worker.min.js', 6 import.meta.url, 7).toString(); 8 9const PdfViewer = ({ fileUrl }) => { 10 11 const [pageNumber, setPageNumber] = useState(1); 12 const [numPages, setNumPages] = useState(null); 13 14 const onDocumentLoadSuccess = ({ numPages }) => { 15 setNumPages(numPages); 16 }; 17 18 const goToPrevPage = () => { 19 setPageNumber((prevPageNumber) => Math.max(prevPageNumber - 1, 1)); 20 }; 21 22 const goToNextPage = () => { 23 setPageNumber((prevPageNumber) => Math.min(prevPageNumber + 1, numPages)); 24 }; 25 26 return ( 27 <div> 28 <Document file={fileUrl} onLoadSuccess={onDocumentLoadSuccess}> 29 <Page pageNumber={pageNumber} /> 30 </Document> 31 <div> 32 <button onClick={goToPrevPage} disabled={pageNumber <= 1}> 33 Previous 34 </button> 35 <button onClick={goToNextPage} disabled={pageNumber >= numPages}> 36 Next 37 </button> 38 </div> 39 <p> 40 Page {pageNumber} of {numPages} 41 </p> 42 </div> 43 ); 44}; 45 46export default PdfViewer; 47
In this PdfViewerWithControls component, we've added two buttons to navigate to the previous and next pages. We use the React state to keep track of the current page number and the total number of pages in the document. The onDocumentLoadSuccess callback updates the total page count, while the goToPrevPage and goToNextPage functions update the current page number.
Accessibility and mobile responsiveness are critical aspects of modern web development. To make your PDF viewer accessible and user-friendly on mobile devices, consider the following:
Incorporating a PDF viewer into your React application doesn't have to be a daunting task. With the React-PDF library, you can seamlessly display PDF documents, offering users a native, in-app experience for interacting with PDFs. By following the steps outlined in this blog, you've learned how to set up React-PDF, load and render PDF pages, customize the viewer's appearance, and add navigation controls to enhance user interaction. You can ensure that your PDF viewer provides a seamless and inclusive experience. With React-PDF, you have the tools to create a robust and user-friendly PDF viewer that enhances the functionality of your React app.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.