react-doc-viewer

repository·master·Indexed 18 days ago

https://github.com/alcumus/react-doc-viewer

A React component for rendering online and local documents, including PDF, images, and DOCX. It supports remote URLs and local files, providing built-in renderers (such as PDFRenderer, HTMLRenderer, and MSDocRenderer) and the ability to implement custom renderers, custom file loaders, and themed UI overrides.

Tokens
8.7K
Snippets
40
Records
41
Agent score
62%

What's inside react-doc-viewer

  1. Create a custom renderer

    master

    A custom renderer is a functional component of type DocRenderer that you define for your project. It receives mainState (containing currentDocument) as a prop. To make the renderer work, you must assign fileTypes (an array of extensions or MIME types) and a weight (higher numbers take precedence over lower numbers; included renderers have a weight of 0) to the component function.

    import React from "react";
    import DocViewer, { DocRenderer } 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;
    
    // Usage
    <DocViewer
      pluginRenderers={[MyCustomPNGRenderer]}
      documents={[{ uri: "/path/to/image.png" }]}
    />
  2. Style the DocViewer component

    master

    There are several ways to apply styles to the DocViewer:

    • CSS Class: Pass a className to the component, which applies to the main div container.
    • React Inline: Use the style prop for inline object-based styling.
    • Styled Components: Wrap the component using styled(DocViewer).
    • CSS Selectors: Target specific internal elements using their DOM IDs (e.g., #react-doc-viewer #header-bar).
    // CSS Class
    <DocViewer documents={docs} className="my-doc-viewer-style" />
    
    // React Inline
    <DocViewer documents={docs} style={{width: 500, height: 500}} />
    
    // StyledComponent
    import styled from "styled-components";
    const MyDocViewer = styled(DocViewer)`
      border-radius: 10px;
    `;
    <MyDocViewer documents={docs} />
  3. Implement a custom FileLoader function

    master

    To extend react-doc-viewer with custom loading logic, you can provide a function that conforms to the FileLoaderFunction type. A file loader is responsible for fetching the document and notifying the viewer when the reading process is complete via a callback.

    Each loader receives a FileLoaderFuncProps object containing:

    • documentURI: The string URI of the file to load.
    • signal: An AbortSignal used to cancel the fetch request.
    • fileLoaderComplete: A callback function (FileLoaderComplete) that must be called once the file has been read. This callback can optionally receive a FileReader instance.

    If you want to use standard browser reading methods, you can use the built-in loaders provided by the library.

    import { FileLoaderFunction } from 'react-doc-viewer';
    
    const myCustomLoader: FileLoaderFunction = ({ documentURI, signal, fileLoaderComplete }) => {
      fetch(documentURI, { signal })
        .then(res => res.blob())
        .then(blob => {
          const reader = new FileReader();
          reader.onloadend = () => fileLoaderComplete(reader);
          reader.readAsDataURL(blob);
        });
    };
  4. Configure DocViewer header settings

    master

    The config prop allows you to control header behavior. You can enable or disable the header, the filename display, and control whether URL parameters are retained.

    <DocViewer 
      documents={docs} 
      config={{
        header: {
          disableHeader: false,
          disableFileName: false,
          retainURLParams: false
        }
      }}
    />
  5. Apply a theme to DocViewer

    master

    You can customize the visual appearance of the viewer by providing a theme object to the theme prop. Available properties include colors for primary, secondary, and tertiary elements, text colors, and scrollbar settings.

    <DocViewer
      documents={docs}
      theme={{
        primary: "#5296d8",
        secondary: "#ffffff",
        tertiary: "#5296d899",
        text_primary: "#ffffff",
        text_secondary: "#5296d8",
        text_tertiary: "#00000099",
        disableThemeScrollbar: false,
      }}
    />
  6. Configure the header via IConfig

    master

    The config prop allows you to customize the document header using IHeaderConfig:

    • disableHeader (boolean): Hides the header component.
    • disableFileName (boolean): Hides the file name in the header.
    • retainURLParams (boolean): Whether to retain URL parameters.
    • overrideComponent (IHeaderOverride): A function that returns a custom React element to replace the default header.
    interface IHeaderConfig {
      disableHeader?: boolean;
      disableFileName?: boolean;
      retainURLParams?: boolean;
      overrideComponent?: () => ReactElement<any, any> | null;
    }
  7. Apply a custom theme with ITheme

    master

    Use the theme prop to control the visual appearance of the viewer. Available keys include:

    • primary, secondary, tertiary: Color strings for different UI layers.
    • text_primary, text_secondary, text_tertiary: Color strings for text elements.
    • disableThemeScrollbar (boolean): Whether to disable the themed scrollbar.
    const myTheme: ITheme = {
      primary: '#333',
      text_primary: '#000',
      disableThemeScrollbar: false
    };
  8. Basic usage of DocViewer

    master

    To use DocViewer, provide an array of document objects to the documents prop. Each object must contain a uri pointing to either a remote URL or a local file path.

    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} />;
    }
  9. Configure included renderers

    master

    By default, DocViewer may not include all renderers. You can explicitly provide renderers via the pluginRenderers prop. You can either pass the DocViewerRenderers array (which contains all included renderers) or an array of specific individual renderers.

    import DocViewer, { DocViewerRenderers, PDFRenderer, PNGRenderer } from "react-doc-viewer";
    
    // Option 1: Use all included renderers
    <DocViewer
      pluginRenderers={DocViewerRenderers}
      documents={docs}
    />
    
    // Option 2: Use specific individual renderers
    <DocViewer
      pluginRenderers={[PDFRenderer, PNGRenderer]}
      documents={docs}
    />
  10. Override the Header component

    master

    You can replace the default header with a custom React element by providing a callback to config.header.overrideComponent. The callback receives state (the current component state), previousDocument, and nextDocument (navigation functions). This function is re-called whenever the mainState updates.

    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
      documents={docs}
      config={{
        header: {
          overrideComponent: myHeader,
        },
      }}
    />
  11. Customize the header with IHeaderOverride

    master

    To completely replace the header, provide a function to overrideComponent in the IHeaderConfig. The function receives an object containing the current state and navigation controls:

    • state: The current IMainState (includes currentFileNo, documents, currentDocument, etc.).
    • previousDocument: A function to navigate to the previous document.
    • nextDocument: A function to navigate to the next document.
    const MyCustomHeader = ({ state, previousDocument, nextDocument }) => (
      <div>
        <span>File: {state.currentDocument?.uri}</span>
        <button onClick={previousDocument}>Prev</button>
        <button onClick={nextDocument}>Next</button>
      </div>
    );
    
    // Usage in DocViewer
    <DocViewer 
      config={{ 
        header: { 
          overrideComponent: () => <MyCustomHeader /> 
        } 
      }} 
      documents={...} 
    />