Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-doc-viewer

Alcumus110.2kISC0.1.14TypeScript support: included

Document viewer for react. Renders online/local documents.

readme

react-doc-viewer

Contents



Current Renderable File Types

Extension MIME Type Available
bmp image/bmp
doc application/msword
docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
htm text/htm
html text/html
jpg image/jpg
jpeg image/jpeg
pdf application/pdf
png image/png
ppt application/vnd.ms-powerpoint
pptx applicatiapplication/vnd.openxmlformats-officedocument.presentationml.presentation
tiff image/tiff
txt text/plain
xls application/vnd.ms-excel
xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet


Installation

Core

 npm i react-doc-viewer
 # or
 yarn add react-doc-viewer

Usage

Warning - By default the component height will expand and contract to the current loaded file. The width will expand to fill the parent.



Basic

DocViewer requires at least an array of document objects to function. Each document object must have a uri to a file, either a url that returns a file or a local file.

import DocViewer from "react-doc-viewer";

function App() {
  const docs = [
    { uri: "https://url-to-my-pdf.pdf" },
    { uri: require("./example-files/pdf.pdf") }, // Local File
  ];

  return <DocViewer documents={docs} />;
}

Included Renderers

To use the included renderers. DocViewerRenderers is an Array of all the included renderers.

import DocViewer, { DocViewerRenderers } from "react-doc-viewer";

<DocViewer
  pluginRenderers={DocViewerRenderers}
  {/* ... */}
/>;

Or you can import individual renderers.

import DocViewer, { PDFRenderer, PNGRenderer } from "react-doc-viewer";

<DocViewer
  pluginRenderers={[PDFRenderer, PNGRenderer]}
  {/* ... */}
/>;


Custom Renderer

To create a custom renderer, that will just exist for your project.

import React from "react";
import DocViewer from "react-doc-viewer";

const MyCustomPNGRenderer: DocRenderer = ({
  mainState: { currentDocument },
}) => {
  if (!currentDocument) return null;

  return (
    <div id="my-png-renderer">
      <img id="png-img" src={currentDocument.fileData as string} />
    </div>
  );
};

MyCustomPNGRenderer.fileTypes = ["png", "image/png"];
MyCustomPNGRenderer.weight = 1;

And supply it to DocViewer > pluginRenderers inside an Array.

import DocViewer, { DocViewerRenderers } from "react-doc-viewer";

<DocViewer
  pluginRenderers={[MyCustomPNGRenderer]}
  documents={
    [
      // ...
    ]
  }
/>;


Custom File Loader

If you need to prevent the actual loading of the file by react-doc-viewer. you can decorate your custom renderer with a callback to do as you wish. e.g. Load the file yourself in an iFrame.

MyCustomPNGRenderer.fileLoader = ({
  documentURI,
  signal,
  fileLoaderComplete,
}) => {
  myCustomFileLoaderCode().then(() => {
    // Whenever you have finished you must call fileLoaderComplete() to remove the loading animation
    fileLoaderComplete();
  });
};


Themed

You can provide a theme object with one or all of the available properties.

<DocViewer
  documents={docs}
  theme={{
    primary: "#5296d8",
    secondary: "#ffffff",
    tertiary: "#5296d899",
    text_primary: "#ffffff",
    text_secondary: "#5296d8",
    text_tertiary: "#00000099",
    disableThemeScrollbar: false,
  }}
/>

Styling

Any styling applied to the <DocViewer> component, is directly applied to the main div container.

- CSS Class

<DocViewer documents={docs} className="my-doc-viewer-style" />

- CSS Class Default Override

Each component / div already has a DOM id that can be used to style any part of the document viewer.

#react-doc-viewer #header-bar {
  background-color: #faf;
}

- React Inline

<DocViewer documents={docs} style={{width: 500, height: 500}} />

- StyledComponent

import styled from "styled-components";
//...
<MyDocViewer documents={docs} />;
//...
const MyDocViewer = styled(DocViewer)`
  border-radius: 10px;
`;

Config

You can provide a config object, which configures parts of the component as required.

<DocViewer documents={docs} config={{
 header: {
  disableHeader: false,
  disableFileName: false,
  retainURLParams: false
 }
}} />


Contributing

Creating a Renderer Plugin

Step 1 - Create a new folder inside src/plugins.

e.g. src/plugins/jpg

Inside this folder, create a Renderer React Typescript file.

e.g. index.tsx

Step 2 - Inside JPGRenderer, export a functional component of type DocRenderer

import React from "react";
import { DocRenderer } from "../../types";

// Be sure that Renderer correctly uses type DocRenderer
const JPGRenderer: DocRenderer = ({ mainState: { currentDocument } }) => {
  if (!currentDocument) return null;

  return (
    <div id="jpg-renderer">
      <img id="jpg-img" src={currentDocument.fileData as string} />
    </div>
  );
};

export default JPGRenderer;

// List the MIME types that this renderer will respond to
JPGRenderer.fileTypes = ["jpg", "jpeg", "image/jpg", "image/jpeg"];

// If you have more than one renderer for the same MIME type, use weight. higher is more preferable.
// Included renderers have a weight of zero
JPGRenderer.weight = 1;

If you are creating a new renderer, also update src/plugins/index.ts with an import to your new renderer file, and Export it as part of the DocViewerRenderers Array.

// ...
import JPGRenderer from "./jpg";

export const DocViewerRenderers = [
  // ...
  JPGRenderer,
];


Overriding Header Component

You can pass a callback function to config.header.overrideComponent that returns a React Element. The function's parameters will be populated and usable, this function will also be re-called whenever the mainState updates. Parameters include the state object from the main component, and document navigation functions for previousDocument and nextDocument.

Example:


const myHeader: IHeaderOverride = (state, previousDocument, nextDocument) => {
    if (!state.currentDocument || state.config?.header?.disableFileName) {
      return null;
    }

    return (
      <>
        <div>{state.currentDocument.uri || ""}</div>
        <div>
          <button
            onClick={previousDocument}
            disabled={state.currentFileNo === 0}
          >
            Previous Document
          </button>
          <button
            onClick={nextDocument}
            disabled={state.currentFileNo >= state.documents.length - 1}
          >
            Next Document
          </button>
        </div>
      </>
    );
  };

<DocViewer
  pluginRenderers={DocViewerRenderers}
  documents={
    {
      /**/
    }
  }
  config={{
    header: {
      overrideComponent: myHeader;
      },
    },
  }
/>

API


DocViewer props

name type
documents IDocument[]
className? string
style? React.CSSProperties
config? IConfig
theme? ITheme
pluginRenderers? DocRenderer[]

IDocument

name type
uri string
fileType? string
fileData? `string

IConfig

name type
header? IHeaderConfig

IHeaderConfig

name type
disableHeader? boolean
disableFileName? boolean
retainURLParams? boolean
overrideComponent? IHeaderOverride

IHeaderOverride () => ReactElement<any, any> | null

name type
state IMainState
previousDocument () => void
nextDocument () => void
returns `ReactElement<any, any>

ITheme

name type
primary? string
secondary? string
tertiary? string
text_primary? string
text_secondary? string
text_tertiary? string
disableThemeScrollbar? boolean

DocRenderer extends React.FC<DocRendererProps>

name type
fileTypes string[]
weight number
fileLoader? FileLoaderFunction `

FileLoaderFunction

(props: FileLoaderFuncProps) => void


FileLoaderFuncProps

name type
documentURI string
signal AbortSignal
fileLoaderComplete FileLoaderComplete

FileLoaderComplete

name type
fileReader FileReader

DocRendererProps

name type
mainState IMainState

IMainState

name type
currentFileNo number
documents IDocument[]
documentLoading? boolean
currentDocument? IDocument
rendererRect? DOMRect
config? IConfig

changelog

0.1.15 (2024-07-31)

0.1.14 (2024-07-31)

Bug Fixes
Other Changes
  • possible fix for cjs support" (89b674c5)

0.1.13 (2024-06-21)

0.1.12 (2024-06-21)

0.1.11 (2024-05-14)

0.1.10 (2024-05-14)

0.1.9 (2024-05-14)

0.1.8 (2024-05-14)

Chores
  • deps: update dependency react-pdf to v8 (f54d0585)

0.1.7 (2024-05-13)

Chores
  • deps: update dependency pdfjs-dist to v4 (556a0956)

0.1.6 (2024-05-13)

0.1.5 (2020-10-29)

Bug Fixes
  • TIFFRenderer file Corrupt: Don't crash if parseTIFF fails because of corrupted file. (30755e57)

0.1.4 (2020-10-29)

Bug Fixes
  • TIFFRenderer crash: If parseTiff is supplied with an undefined tiffArrayBuffer. Return out. (eedeac1e)

0.1.3 (2020-10-29)

New Features
  • TIF: Added .tif as an option to render within TIFFRenderer. (a32f9b0f)
Other Changes

0.1.2 (2020-10-26)

Bug Fixes
  • Added github url to npm package (b713957f)

0.1.1 (2020-10-26)

New Features
  • FileName Header:
    • decodeURI when rendering fileName in header title (79c0da83)
    • When rendering fileName in header, remove url params unless requested to keep (109da8d7)

0.0.43 (2020-09-30)

New Features
  • Combine File Loaders: File Loaders duplicate code combined, also base64 and arrayBuffer combined into fileData (#47) (f3fd9952)

0.0.42 (2020-09-30)

Documentation Changes
  • README - styled component example is missing a closing bracket after DocViewer Fixes #31 (da0a40ee)
New Features
  • BMP Image renderer added (2e8578b1)
  • Internal ImageProxyRenderer created, that can be used by all other Image renderers, and styled by them (dc2afb71)
Other Changes
  • Alcumus/react-doc-viewer into develop (2184d46c)
  • mattmogford-alcumus/40_Create-HTMLRenderer (9eff64e2)

0.0.41 (2020-09-25)

0.0.40 (2020-09-24)

Documentation Changes
  • README - styled component example is missing a closing bracket after DocViewer Fixes #31 (7964c0b9)
New Features
  • BMP Image renderer added (2cb03e4c)
  • Internal ImageProxyRenderer created, that can be used by all other Image renderers, and styled by them (90e575da)

0.0.39 (2020-09-23)

Documentation Changes
  • README updated (819acb5b)

0.0.38 (2020-09-23)

New Features
  • Added renderer for .msg file extension (b4cf7bf4)
  • useDocumentLoader hook now allows use of custom fileLoaders. e.g. bse64, ArrayBuffer (ebc9a454)

0.0.37 (2020-09-18)

Other Changes
  • mattmogford-alcumus/issue29 (35ea44eb)

0.0.36 (2020-09-17)

0.0.35 (2020-09-17)

0.0.34 (2020-09-16)

Bug Fixes
  • Document fetches header even if file type is supplied (b5296d0f)

0.0.33 (2020-09-16)

Other Changes
  • develop (66cd5676)
  • mattmogford-alcumus/issue19 (f8f16bc1)

0.0.32 (2020-09-03)

Chores
  • Added default height to loading container (e5570741)
New Features
  • pluginRenderers are now passed directly to the main state context, and the correct renderer is retrieved from there depending on it's fileType associations (4c7abfd3)
Bug Fixes
Tests
  • Updated test snapshot (7660907f)

0.0.31 (2020-09-02)

Chores
  • Removed unused css file (485f15b3)
New Features
  • Removed FontAwesome and included replacement svgs, which are resizable and colourable (7c7c3fca)
Bug Fixes
  • IIconProps import type fixed (1e1b00c5)
Tests
  • Updated snapshots for tests (f40a5447)

0.0.30 (2020-09-02)

New Features
  • implemented ability to fully replace the contents of the header, but also retain access to the state and document navigation actions (2c1e3d0d)

0.0.29 (2020-09-01)

Chores
  • No longer require public folder (2a639dcc)

0.0.28 (2020-09-01)

Bug Fixes
  • Removed necessity for 2 context calls (1e9886ca)

0.0.27 (2020-09-01)

Documentation Changes
  • Removed Setup Demo from contents at top of README (8a8db314)

0.0.26 (2020-09-01)

Bug Fixes
  • Pass mainState context to CurrentRenderer for ease of use/access to loaded data, and other mainState props (98efa91c)

0.0.25 (2020-09-01)

Chores
  • Renamed MainContext to DocViewerContext for external plugins to import it with a less generic name (c433d438)
Documentation Changes
  • Added README info for importing and using the included individual renderers (3a87cf87)
Refactors
  • Reverting from Recoil to react state, context and reducers (ff26a49b)

0.0.24 (2020-08-28)

0.0.23 (2020-08-28)

0.0.22 (2020-08-28)

New Features
  • Merge Default Plugins: Plugins have been pulled back into the component package, Updated README to inform on updated and better way to use included and custom plugins (34bed0c7)
Bug Fixes
  • If user passes in a bad file / url and uri ends up not being useful, (ae99034f)

0.0.21 (2020-08-27)

Chores
  • Removed old pdf plugin dependencies (3baa9355)

0.0.20 (2020-08-27)

0.0.19 (2020-08-26)

Documentation Changes
  • README updated (39fd2b93)
Bug Fixes
  • FileType removed, as the component needs to be ambiguous to plugin renderers (fcf9e1c0)

0.0.18 (2020-08-26)

0.0.17 (2020-08-25)

0.0.16 (2020-08-25)

0.0.15 (2020-08-25)

0.0.14 (2020-08-25)

0.0.13 (2020-08-25)

0.0.12 (2020-08-25)

Chores
  • Tidied state atoms etc. (fbb5ede2)
Bug Fixes
  • PDFRenderer Reset Zoom Broken: resetZoomLevel function wasn't being called (4b3b9918)

0.0.12 (2020-08-25)

Bug Fixes
  • PDFRenderer Reset Zoom Broken: resetZoomLevel function wasn't being called (4b3b9918)

0.0.11 (2020-08-25)

Bug Fixes
  • sever was incorrect for build-release options (2ebe713b)
Tests
  • Added example png for testing purposes (9c3c6cf6)

0.0.10 (2020-08-24)

0.0.9 (2020-08-24)

0.0.8 (2020-08-24)

Bug Fixes
  • ignore index on building package, point main and types to main component file DocViewer.tsx (96f1a12f)

0.0.4 (2020-08-24)

New Features
  • Versioning: Added scripts for auto update CHANGELOG with versioning (31c31d1c)
Bug Fixes
  • config is optional and so could be undefined (596d611d)

0.0.3 (2020-08-24)

New Features
  • Versioning: Added scripts for auto update CHANGELOG with versioning (48536a0c)
Bug Fixes
  • config is optional and so could be undefined (596d611d)

0.0.3 (2020-08-24)

Bug Fixes
  • config is optional and so could be undefined (596d611d)