A React component to view a PDF document

Last update: Jun 21, 2022

React PDF viewer

A React component to view a PDF document. It's written in TypeScript, and powered by React hooks completely.

// Core viewer
import { Viewer } from '@react-pdf-viewer/core';

// Plugins
import { defaultLayoutPlugin } from '@react-pdf-viewer/default-layout';

// Import styles
import '@react-pdf-viewer/core/lib/styles/index.css';
import '@react-pdf-viewer/default-layout/lib/styles/index.css';

// Create new plugin instance
const defaultLayoutPluginInstance = defaultLayoutPlugin();

<Viewer
    fileUrl='/assets/pdf-open-parameters.pdf'
    plugins={[
        // Register plugins
        defaultLayoutPluginInstance,
        ...
    ]}
/>

React PDF viewer

Features

Basic features

  • Support password protected document
  • Zooming: Support custom levels such as actual size, page fit, and page width
  • Navigation between pages
  • Can go to the first and last pages quickly
  • Search for text
  • Preview page thumbnails
  • View and navigate the table of contents
  • List and download attachments
  • Rotating
  • Text selection and hand tool modes
  • Different scrolling modes
  • Full screen mode
  • Can open a file from local. Users can drag and drop a local file to view it
  • Download file
  • View the document properties
  • Support SSR
  • Print

Customization

  • The toolbar can be customized easily
  • All text items can be localized in another language

Coming soon

  • Theming
  • Darkmode

License

You have to purchase a Commercial License at the official website.

About

This project is developed by Nguyen Huu Phuoc. I love building products and sharing knowledge.

Be my friend on

Products

You might be interested in my products:

1 LOC (3.3kβ˜…)

Favorite JavaScript utilities in single line of code

Blur Page

A browser extension to hide sensitive information on a web page

Check Browsers Support

A browser extension to check browser compatibility without leaving your tab

CSS Layout (2.7kβ˜…)

A collection of popular layouts and patterns made with CSS

Fake Numbers

Generate fake and valid numbers

Form Validation

The best validation library for JavaScript

HTML DOM (3.1kβ˜…)

How to manage HTML DOM with vanilla JavaScript

React PDF Viewer

A React component to view a PDF document

this VS that

The differences between ___ and ___ in the front-end development

GitHub

https://github.com/phuoc-ng/react-pdf-viewer
Comments
  • 1. Loading a large pdf on Safari iOS and macOS causes a crash

    [Warning] Total canvas memory use exceeds the maximum limit (384 MB). (2.c9af885f.chunk.js, line 2)
    [Error] TypeError: null is not an object (evaluating 'r.canvasContext.canvas')
    
    Reviewed by esetnik at 2021-03-15 15:14
  • 2. Viewer does not render signature fields

    Hello there,

    I'm using your wonderful lib on a new project I'm working on for my company and I ran into an issue today. If a try to render with your viewer a PDF which contains signature fields, they are just simply ignored 😱

    You can reproduce it by going to the home then use the action button "Open file" to open any PDF that has signature fields. For example, this the the PDF I'm using : test.pdf

    Any help on this issue would be very much appreciated because right now I can't display contracts with electronic signature to the users 😭

    Don't hesitate if you need more infos! Thank you ☺️

    Reviewed by fmigot at 2021-01-18 17:21
  • 3. Error: Invalid parameter object: need either .data, .range or .url

    Hi , i am trying to show a pdf file, and i got this error . Error: Invalid parameter object: need either .data, .range or .url

    my implementation :

    <Worker workerUrl="https://unpkg.com/[email protected]/build/pdf.worker.min.js"> <div style={{ height: "750px" }}> <Viewer fileUrl={documentURL} /> </div> </Worker>

    Reviewed by David-moonsite at 2020-09-07 10:47
  • 4. v3.1.0: document content is hidden

    Hello,

    The issue occurred after react-pdf-viewer version update from 3.0.0 to 3.1.0. Document content is hidden on initial load however, the viewer displays the content as expected after actions such as mouse hover on one of the toolbar elements or navigation with a keyboard. For reference, I'm providing your own sample with updated react-pdf-viewer versions to 3.1.0.

    https://codesandbox.io/s/react-pdf-viewer-sample-forked-xhvqm

    Reviewed by MPuida at 2022-01-31 14:46
  • 5. pdfjs 2.7.570 breaks build for Create-React-Apps

    I just want to leave that here: As with the latest versions of pdfjs-dist, my CRA app is broken as decribed here. I have no idea whether or not this might be a pdfjs problem, or if it might be related to react-pdf-viewer.

    Any insights are highly appreciated.

    Reviewed by aspnetde at 2021-04-14 11:51
  • 6. Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

    I installed

    "@react-pdf-viewer/core": "^2.0.1",
    "pdfjs-dist": "2.3.200",
    ...
    "react": "^16.12.0",
    "react-dom": "^16.12.0"
    

    Importing and rendering the worker in a high-level component:

    import { Worker } from '@react-pdf-viewer/core';
    <Worker workerUrl="https://unpkg.com/[email protected]/build/pdf.worker.min.js"}>
        {children}
    </Worker>
    

    Note: I'm using the downgraded version of pdfjs-dist as suggested here https://github.com/react-pdf-viewer/react-pdf-viewer/issues/263#issuecomment-672964145 and here https://github.com/react-pdf-viewer/react-pdf-viewer/issues/276#issuecomment-688312715

    And the Viewer:

    import { Viewer } from '@react-pdf-viewer/core';
    import '@react-pdf-viewer/core/lib/styles/index.css';
    
    <Viewer fileUrl="https://www.morganstanley.com/about-us-ir/shareholder/3q2020.pdf" />;
    

    And I'm getting this error when trying to load the page:

    Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component
    ...
    at Viewer (core.js:2944)
    
    Reviewed by mmichael0413 at 2020-10-26 18:06
  • 7. Click to open link on pdf when link not hyperlink

    Hello, I did a test by creating a simple example of pdf without hyperlink, I put https://google.fr and check it in the pdf reader, the link is not clickable, however, if the link is in hyperlink via libreoffice or other, the link is clickable :)

    I did the same test with the native pdf reader of google chrome and whether in hyperlink or not, it detects that it is a link and allows to be able to click on it

    Would it be possible to think of this scenario?

    Indeed, the standard is respected but I do not think that the agents (I work for a company recognized as a training organization / education) will have the idea of ​​creating hyperlinks while they make their pdf

    I could put a very quick example on a codesanbox or share the two pdf to dissociate the two cases, if necessary :)

    Thank you again for taking the time to read me.

    Reviewed by JSurquin at 2020-04-28 10:21
  • 8. Highlight using x/y coordinates and page numbers

    Hello @phuoc-ng and Team,

    I have a use case where I want to highlight certain words and sentences using their x/y coordinates and page numbers that will be sent from the backend api. As per my understanding, we do not currently have a feature/plugin for that.

    • I tried highlighting using keywords api in the search plugin but it highlights all instances of the word.
    • Highlight plugin can only be activated on text selection.

    Can you guide me on how to achieve this functionality using the current version and if not, can I make a feature request for the same? We at our organization are very much interested in buying the commercial license for our purpose and this highlight functionality is an integral part of our product.

    Thank You!

    Reviewed by dsac147 at 2021-09-27 03:31
  • 9. Password filled programmatically

    I have a question about protected pdf. I uploaded a pdf with password in viewer and it asked to me password. Can i fill this form and submit programmatically, for example automatically onPdfLoaded ?

    Thanks

    Reviewed by lillogoal at 2021-09-09 19:04
  • 10. PDF Viewer loads pdf but blank on initial load

    Issue:

    I have several PDFs that when the initial page is loaded that they will not display.

    Example of what it looks like blank-pdf-on-load

    Example 2 with multiple pages blank-pdf-on-load-ex2

    To reproduce

    1. Put the pdfs in the project
    2. Ensure that all packages are up to date
    3. Come to the page
    4. React pdf viewer will initially be blank until you scroll or manipulate the PDF viewer

    After you scroll or pull out the pages it will display pdf-loaded-after-scroll

    Additional:

    I searched for issues and the only thing I found similar was #909, so in response I have upgraded all packages for the project. nothing-to-update

    I have used multiple browsers and found the same issue. I am using Vivaldi but most of my team is using Chrome or Edge.

    Example PDF that is not working for me NOT_LOADING.pdf

    Thanks in advance Will

    Reviewed by ZinkNotTheMetal at 2022-02-15 15:57
  • 11. Initialize with search words highlighted

    It is possible to init the PDF with a page number so it opens on that page. We also need to pass one or more search words (from an external search) and have react-pdf-viewer put those search words into the search box and immediately highlight the matching words on that particular page.

    Reviewed by janhoy at 2020-09-10 06:58
  • 12. Search isn't working with updated package

    I'm using the updated package and wanted to implement searching functionality and I'm gating an error like TypeError: Cannot read properties of undefined (reading 'map') at search.js:151:1 when submitting enter button for searching.

    Package:

    image

    Component:

    import { Viewer, Worker } from '@react-pdf-viewer/core';
    import { defaultLayoutPlugin } from '@react-pdf-viewer/default-layout';
    import { pageNavigationPlugin } from "@react-pdf-viewer/page-navigation";
    import { searchPlugin } from '@react-pdf-viewer/search';
    
    // import PDFList from './components/PDFList';
    
    
    function App() {
      // const data: IPDFList[] = Data
      const defaultLayoutPluginInstance = defaultLayoutPlugin();
      const searchPluginInstance = searchPlugin();
      const pageNavigationPluginInstance = pageNavigationPlugin();
      const { ShowSearchPopoverButton } = searchPluginInstance;
      const {
        CurrentPageInput,
        GoToFirstPageButton,
        GoToLastPageButton,
        GoToNextPageButton,
        GoToPreviousPage
      } = pageNavigationPluginInstance;
      const currentPage = localStorage.getItem("current-page");
      const initialPage = currentPage ? parseInt(currentPage, 10) : 0;
    
      const handlePageChange = (e: any) => {
        localStorage.setItem("current-page", `${e.currentPage}`);
      };
    
    
      return (
        <>
          <div className="p-4">
            <div className='max-w-4xl w-full mx-auto'>
              <h1 className='text-4xl text-center mt-4 mb-7 font-bold text-purple-600'>PDF Read and Search</h1>
              {/* <PDFList lists={data} /> */}
              <div className="">
                <Worker workerUrl="https://unpkg.com/[email protected]/build/pdf.worker.min.js">
    
                  <div
                    className="rpv-core__viewer flex flex-col h-full border border-solid border-black border-opacity-30"
    
                  >
                    <div className='flex items-center bg-[#eeeeee] border-b border-black border-opacity-10 p-1'>
                      <ShowSearchPopoverButton />
                      <div className='px-1'>
                        <GoToFirstPageButton />
                      </div>
                      <div className='px-1'>
                        <GoToPreviousPage />
                      </div>
                      <div className='px-1'>
                        <CurrentPageInput />
                      </div>
                      <div className='px-1'>
                        <GoToNextPageButton />
                      </div>
                      <div className='px-1'>
                        <GoToLastPageButton />
                      </div>
                    </div>
                    <div className='flex-1 overflow-hidden'></div>
                    <div className='h-[30rem]'>
                      <Viewer
                        fileUrl={`/recources/Angular_Router_Crash_Course.pdf`}
                        initialPage={initialPage}
                        onPageChange={handlePageChange}
                        plugins={[searchPluginInstance, pageNavigationPluginInstance]}
                        defaultScale={1}
                      />
                    </div>
                  </div>
    
                </Worker>
              </div>
    
            </div>
          </div>
    
        </>
      );
    }
    
    export default App;
    
    Reviewed by akib1997 at 2022-06-19 12:11
  • 13. Viewer crash for long pdf with specific window width

    I created a reproduction repo https://github.com/xiaody/react-pdf-viewer-issue . It's a CRA project with App.js edited to

    import * as React from 'react';
    
    // Core viewer
    import { Viewer, Worker } from '@react-pdf-viewer/core';
    
    // Import styles
    import '@react-pdf-viewer/core/lib/styles/index.css';
    
    <Viewer fileUrl="/assets/pdf-open-parameters.pdf" />;
    
    export default function App() {
      return (
        <Worker workerUrl='https://ccsp.gtimg.com/ccsp/js/v2.0/worker/pdf.worker-es5.min.js'>
          <Viewer fileUrl="/pytest.pdf" />
        </Worker>
      );
    }
    

    The file pytest.pdf has 200+ pages, weight 933KB.

    Clone the repo and run npm start. When your window is at specific width, chances are that you see Uncaught Error: Maximum update depth exceeded.

    image

    With a debugger in the measureRef function, I can see the setCacheMeasure function is called many times. Not sure if it's the cause.

    image
    Reviewed by xiaody at 2022-06-15 02:33
  • 14. Keep Toolbar on Error

    Hi,

    Is there a way to keep the default layout + toolbar when a pdf error occurs?

    Alternatively, is there a way to open a PDF file from renderError? The viewer doesn't seem to be there after the errors get rendered. I'd like to allow a user to upload and view a PDF if/after an error occurs.

    Reviewed by readefine-app at 2022-06-14 19:45
  • 15. Customising the print loader

    Is there a way to customise the print loader?

    I'm looking for a way to pass in a custom print loader renderer, like the default loader renderer.

    Thanks!

    Reviewed by yjrandom at 2022-06-14 01:20
  • 16. How to apply margins between pages?

    Hi there! I was wondering about the proper way to apply a margin between pages. My approach was to add margin to rpv-core__inner-page class, but that does not seem to work (page navigation gets broken). At the moment, when I render my PDF i get very little space between pages (see screenshot) image

    Thanks in advance!

    Reviewed by RadomirNowak at 2022-06-08 10:29
  • 17. Ability to add custom options to more actions menu

    Is there a way to add functionality to the more actions menu? We have some custom functionality that we need to add that navigates us to a new page to do some action but is related to the pdf.

    image

    Reviewed by ZinkNotTheMetal at 2022-06-07 13:49
🎯 React component for transportation of modals, lightboxes, loading bars... to document.body or else.

React-portal Struggling with modals, lightboxes or loading bars in React? React-portal creates a new top-level React tree and injects its children int

Jun 24, 2022
Declarative, nested, stateful, isomorphic document.title for React

React Document Title Provides a declarative way to specify document.title in a single-page app. This component can be used on server side as well. Bui

Jun 17, 2022
A document head manager for React
A document head manager for React

React Helmet This reusable React component will manage all of your changes to the document head. Helmet takes plain HTML tags and outputs plain HTML t

Jun 22, 2022
Appends a new DOM node to the end of the `document.body` and renders it's child React tree into it.

@react-lit/portal Appends a new DOM node to the end of the document.body and renders it's child React tree into it. Useful to break out of the DOM hie

Dec 9, 2021
Document Management System API Backend

Document Management System View on Pivotal Tracker The system manages documents, users and roles. Each document defines access rights i.e. which roles

Oct 1, 2021
@use-gesture is a library that let you bind richer mouse and touch events to any component or view.
@use-gesture is a library that let you bind richer mouse and touch events to any component or view.

??Bread n butter utility for component-tied mouse/touch gestures in React

Jun 23, 2022
Jan 23, 2022
✨ View all of your GitHub stats and compare your stats with friends, made using nextjs and tailwind.

✨ View all of your GitHub stats and compare your stats with friends, made using nextjs and tailwind.

May 6, 2022
A simple tool to view Facebook Messenger exported JSON files
A simple tool to view Facebook Messenger exported JSON files

Facebook Messenger exported JSON viewer What's this? This is a simple tool to view Facebook Messenger exported JSON files. I made the UI into a Messen

Jun 8, 2022
:tada: React Universal Hooks : just use****** everywhere (Functional or Class Component). Support React DevTools!
:tada: React Universal Hooks : just use****** everywhere (Functional or Class Component). Support React DevTools!

react-universal-hooks React Universal Hooks : just use****** everywhere. Support React >= 16.8.0 Installation Using npm: $ npm install --save react-un

Jun 12, 2022
React component to blur image backgrounds using canvas.
React component to blur image backgrounds using canvas.

React Blur React component for creating blurred backgrounds using canvas. Live demo Installation npm install react-blur --save Usage var Blur = requir

Jun 5, 2022
πŸ“‘ A React component to easily create demos of other components
πŸ“‘ A React component to easily create demos of other components

React DemoTab ?? A React component to easily create demos of other components Install npm install react-demo-tab Demo DemoTab example Example import R

May 22, 2022
React file input component for complete control over styling and abstraction from file reading.

react-file-reader-input React file input component for complete control over styling and abstraction from file reading. <FileReaderInput as={dataForma

May 22, 2022
The react UI component for building complex filter criteria
 The react UI component for building complex filter criteria

React Filter Control The React component for building the composite filter criteria Demo (JS) | Demo (TS) Together With Data Table Overview Installati

May 22, 2022
React JSON Viewer Component, Extracted from redux-devtools

This package was merged into redux-devtools monorepo. Please refer to that repository for the latest updates, issues and pull requests. react-json-tre

May 31, 2022
πŸ–± A resizable and draggable component for React.
πŸ–±  A resizable and draggable component for React.

A resizable and draggable component for React. Table of Contents Screenshot Live Demo Storybook CodeSandbox Install Usage Props Instance API updateSiz

Jun 22, 2022
πŸ“ A resizable component for React.
πŸ“  A resizable component for React.

?? A resizable component for React. Table of Contents Screenshot Live Demo Storybook CodeSandbox Install Usage Props Instance API updateSize(size: { w

Jun 25, 2022
React split-pane component

React Split Pane Split-Pane React component, can be nested or split vertically or horizontally! Installing npm install react-split-pane # or if you u

Jun 17, 2022
A simple React component to reproduce the way iOS deletes an item in a list
A simple React component to reproduce the way iOS deletes an item in a list

react-swipe-to-delete-ios A simple React component to reproduce the way iOS deletes an item in a list. Demo Installation yarn add react-swipe-to-delet

May 22, 2022