npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-doc-viewer

v0.1.14

Published

Document viewer for react. Renders online/local documents.

Downloads

92,652

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 | ArrayBuffer - Used Internally - Ignored if passed into props |


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> | null |


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 | null | undefined |


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 |