Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to integrate React-PDF in ReactJS ?

  • Difficulty Level : Hard
  • Last Updated : 23 Apr, 2021

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :