How to integrate React-PDF in ReactJS ?

React-PDF is a package that helps users to display PDF files in their React app. By using react-pdf package we can add PDF files in our React app as if they were images. To use the latest version of react-pdf package, our project should use React 16.3 or later. We can integrate react-pdf using the following approach.

Creating React Application And Installing Module:

Step 1: Create a React application using the following command.

npx create-react-app my-app

Step 2: After creating your project folder(i.e. my-app), move to it by using the following command.

cd my-app

Step 3: After creating the React application, Install the react-pdf package using the following command.

npm install react-pdf

Step 4: Add sample.pdf file to my-app/src folder which you want to display.

Project Structure: 

Project Structure

Example: Add the following code in the App.js file. Here, App is our default component where we have written our code.

Javascript




import React from 'react';
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';
import pdfFile from './sample.pdf'
 
function App() {
 
    return (
        <div>
            <Document file={pdfFile}>
                <Page pageNumber={1} />
            </Document>
        </div>
    );
}
 
export default App;


Note: Instead of importing/requiring react-pdf directly, we had used entry points which are being provided by react-pdf because entry points enable PDF.js worker which is crucial for performance.  This makes sure that PDF files will be rendered in a different thread without affecting the performance of the page.

Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output.

Reference: https://www.npmjs.com/package/react-pdf

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button