@cyntler/react-doc-viewer

repository·main·Indexed 19 days ago

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

A React file viewer (v17+) that supports various file types including images, PDFs, and text. It utilizes MS Office online services for rendering Office documents via iframes. The library provides built-in renderers for BMP, HTML, JPG, MSDoc, PDF, PNG, TIFF, TXT, CSV, GIF, Video, and WebP, while allowing for custom renderers and file loaders. It includes features for internationalization, theme customization, and programmatic navigation via DocViewerRef.

Tokens
6.7K
Snippets
31
Records
34
Agent score
67%

What's inside @cyntler/react-doc-viewer

  1. Create a custom renderer

    main

    A custom renderer is a component that implements the DocRenderer interface. It must define fileTypes (an array of strings/MIME types) and a weight (number). You can also define a fileLoader to handle custom pre-fetching logic.

    import React from "react";
    import DocViewer from "@cyntler/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;
    
    // To use it:
    <DocViewer
      pluginRenderers={[MyCustomPNGRenderer]}
      documents={[
        // ...
      ]}
    />
  2. Configure DocViewer options

    main

    The config object allows you to customize various aspects of the DocViewer component, including header behavior, CSV parsing, and PDF viewing settings.

    <DocViewer
      documents={docs}
      config={{
        header: {
          disableHeader: false,
          disableFileName: false,
          retainURLParams: false,
        },
        csvDelimiter: ",", // "," as default
        pdfZoom: {
          defaultZoom: 1.1, // 1 as default
          zoomJump: 0.2, // 0.1 as default
        },
        pdfVerticalScrollByDefault: true, // false as default
      }}
    />
  3. Style the DocViewer component

    main

    You can style the component using className, inline style props, or styled-components. Additionally, you can target 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 }} />
    
    // Styled Components
    import styled from "styled-components";
    const MyDocViewer = styled(DocViewer)`
      border-radius: 10px;
    `;
  4. Configure pre-fetch method and request headers

    main

    By default, the library uses a HEAD request to guess Content-Type. Use prefetchMethod to change this (e.g., to GET for AWS URLs) and requestHeaders to provide authentication tokens or custom headers.

    const headers = {
      "X-Access-Token": "1234567890",
      "My-Custom-Header": "my-custom-value",
    };
    
    <DocViewer 
      documents={docs} 
      prefetchMethod="GET" 
      requestHeaders={headers} 
    />
  5. Configure the DocViewer theme

    main

    Pass a theme object to customize the visual appearance of the viewer. Available properties include primary, secondary, tertiary, textPrimary, textSecondary, textTertiary, and disableThemeScrollbar.

    <DocViewer
      documents={docs}
      theme={{
        primary: "#5296d8",
        secondary: "#ffffff",
        tertiary: "#5296d899",
        textPrimary: "#ffffff",
        textSecondary: "#5296d8",
        textTertiary: "#00000099",
        disableThemeScrollbar: false,
      }}
    />
  6. Basic usage of DocViewer

    main

    To use DocViewer, provide an array of document objects to the documents prop. Each object must contain a uri (a remote URL or a local file path). You must also provide pluginRenderers (typically DocViewerRenderers) to enable file rendering.

    import DocViewer, { DocViewerRenderers } from "@cyntler/react-doc-viewer";
    import "@cyntler/react-doc-viewer/dist/index.css";
    
    function App() {
      const docs = [
        { uri: "https://url-to-my-pdf.pdf" }, // Remote file
        { uri: require("./example-files/pdf.pdf") }, // Local File
      ];
    
      return <DocViewer documents={docs} pluginRenderers={DocViewerRenderers} />;
    }
  7. Display blob or uploaded documents

    main

    To display files uploaded by a user (Blobs), map the File objects to document objects using window.URL.createObjectURL(file) for the uri.

    const DocViewerWithInputApp = () => {
      const [selectedDocs, setSelectedDocs] = useState<File[]>([]);
    
      return (
        <>
          <input
            type="file"
            accept=".pdf"
            multiple
            onChange={(el) =>
              el.target.files?.length &&
              setSelectedDocs(Array.from(el.target.files))
            }
          />
          <DocViewer
            documents={selectedDocs.map((file) => ({
              uri: window.URL.createObjectURL(file),
              fileName: file.name,
            }))}
            pluginRenderers={DocViewerRenderers}
          />
        </>
      );
    };
  8. Override the Loading renderer

    main

    To customize the UI shown while a document is loading, use config.loadingRenderer.overrideComponent.

    By default, the loading component appears if the loading process takes longer than 500ms. You can change this threshold or disable the delay entirely using showLoadingTimeout:

    • Set showLoadingTimeout: false to show the loading component immediately.
    • Set showLoadingTimeout: <number> to provide a custom delay in milliseconds.
    const MyLoadingRenderer = ({ document, fileName }) => {
      const fileText = fileName || document?.fileType || "";
    
      if (fileText) {
        return <div >Loading Renderer ({fileText})...</div>;
      }
    
      return <div >Loading Renderer...</div>;
    };
    
    <DocViewer
      pluginRenderers={DocViewerRenderers}
      documents={[{ uri: '...' }]}
      config={{
        loadingRenderer: {
          overrideComponent: MyLoadingRenderer,
          showLoadingTimeout: false, // false to disable delay, or a number in ms
        },
      }}
    />;
  9. Control document navigation using DocViewerRef

    main

    Since version 1.13.0, you can programmatically control the DocViewer component (e.g., for custom navigation buttons) by using a React ref with the DocViewerRef type. The ref provides methods to navigate through the document list, specifically .prev() to go to the previous document and .next() to go to the next one.

    import DocViewer, { DocViewerRef } from "@cyntler/react-doc-viewer";
    import { useRef }
    
    export const UsingRef = () => {
      const docViewerRef = useRef<DocViewerRef>(null);
    
      return (
        <>
          <div>
            <button onClick={() => docViewerRef?.current?.prev()}>
              Prev Document By Ref
            </button>
            <button onClick={() => docViewerRef?.current?.next()}>
              Next Document By Ref
            </button>
          </div>
          <DocViewer
            ref={docViewerRef}
            documents={docs}
            config={{ header: { disableHeader: true } }}
          />
        </>
      );
    };