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 the 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.
Prerequisite:
- React JS
- React Functional Component
Steps to create 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
Project Structure:
The updated dependencies in package.json file will look like:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-pdf": "^7.6.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}
Example: Add the following code in the App.js file.
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; |
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
Contact Us