vue.js logo

React PDF viewer


To create a React PDF viewer, you can use the @react-pdf-viewer library, which is a popular library for viewing PDFs in React applications. Below is a step-by-step guide to set up a simple React PDF viewer using this library.


Step 1: Install Dependencies

First, install the required dependencies:


npm install @react-pdf-viewer/core @react-pdf-viewer/default-layout

or

yarn add @react-pdf-viewer/core @react-pdf-viewer/default-layout


Step 2: Basic Setup

Create a React component for the PDF viewer.


App.js


                import React from 'react';
            import { Worker, Viewer } from '@react-pdf-viewer/core';
            import '@react-pdf-viewer/core/lib/styles/index.css';
            import '@react-pdf-viewer/default-layout/lib/styles/index.css';
            import { defaultLayoutPlugin } from '@react-pdf-viewer/default-layout';

            const App = () => {
              const defaultLayoutPluginInstance = defaultLayoutPlugin();

              return (
                <div className="App" style={{ height: '100vh' }}>
                  <Worker workerUrl={`https://unpkg.com/pdfjs-dist@${pdfjsVersion}/build/pdf.worker.min.js`}>
                    <div
                      style={{
                        height: '750px',
                        border: '1px solid rgba(0, 0, 0, 0.3)',
                      }}
                    >
                      <Viewer
                        fileUrl="/path/to/your/pdf-file.pdf"
                        plugins={[defaultLayoutPluginInstance]}
                      />
                    </div>
                  </Worker>
                </div>
              );
            };

            export default App;

Step 3: Explanation


Worker: The `Worker` component is used to set up a worker to load the PDF. This improves performance by offloading the PDF rendering to a web worker.


Viewer: The `Viewer` component is the main component that renders the PDF. You need to provide the URL of the PDF file using the `fileUrl` prop.


defaultLayoutPlugin: The `defaultLayoutPlugin` is a plugin provided by `@react-pdf-viewer/default-layout` that adds additional features like a toolbar and sidebar to the PDF viewer.