@abstractops/react-doc-viewer 中文文档教程

发布于 3年前 浏览 18 项目主页 更新于 3年前

react-doc-viewer

Contents



Current Renderable File Types

ExtensionMIME TypeAvailable
bmpimage/bmp
docapplication/msword
docxapplication/vnd.openxmlformats-officedocument.wordprocessingml.document
htmtext/htm
htmltext/html
jpgimage/jpg
jpegimage/jpeg
pdfapplication/pdf
pngimage/png
pptapplication/vnd.ms-powerpoint
pptxapplicatiapplication/vnd.openxmlformats-officedocument.presentationml.presentation
tiffimage/tiff
txttext/plain
xlsapplication/vnd.ms-excel
xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet



Installation

Core

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

Usage

警告 - 默认情况下,组件高度将扩展和收缩到当前加载的文件。 宽度将扩展以填充父级。



Basic

DocViewer 至少需要一组文档对象才能运行。 每个文档对象都必须有一个文件的 uri,可以是返回文件的 url,也可以是本地文件。

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

使用包含的渲染器。 DocViewerRenderers 是所有包含的呈现器的数组。

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

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

或者您可以导入单独的渲染器。

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

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



Custom Renderer

要创建一个自定义渲染器,它只存在于您的项目中。

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;

并将其提供给 DocViewer > Array 中的 pluginRenderers。

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

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



Custom File Loader

如果您需要阻止 react-doc-viewer 实际加载文件。 你可以用回调来装饰你的自定义渲染器来做你想做的事。 例如,自己将文件加载到 iFrame 中。

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



Themed

您可以为主题对象提供一个或所有可用属性。

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

Styling

应用于 组件的任何样式都直接应用于主 div 容器。

- CSS Class

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

- CSS Class Default Override

每个组件/div 都有一个 DOM id,可用于设置文档查看器任何部分的样式。

#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

您可以提供一个配置对象,它根据需要配置组件的各个部分。

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



Contributing

Creating a Renderer Plugin

第 1 步 - 在 src/plugins 中创建一个新文件夹。

例如 src/plugins/jpg

在此文件夹中,创建一个 Renderer React Typescript 文件。

例如 index.tsx

第 2 步 - 在 JPGRenderer 内部,导出 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;


如果您正在创建一个新的渲染器,还更新 src/plugins/index.ts 并导入新的渲染器文件,并将其导出为 DocViewerRenderers Array 的一部分。

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

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



Overriding Header Component

您可以将回调函数传递给返回 React 元素的 config.header.overrideComponent。 该函数的参数将被填充并可用,该函数也将在 mainState 更新时重新调用。 参数包括来自主组件的状态对象,以及previousDocumentnextDocument 的文档导航函数。

示例:

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

nametype
documentsIDocument[]
className?string
style?React.CSSProperties
config?IConfig
theme?ITheme
pluginRenderers?DocRenderer[]

IDocument

nametype
uristring
fileType?string
fileData?string | ArrayBuffer - Used Internally - Ignored if passed into props

IConfig

nametype
header?IHeaderConfig

IHeaderConfig

nametype
disableHeader?boolean
disableFileName?boolean
retainURLParams?boolean
overrideComponent?IHeaderOverride

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

nametype
stateIMainState
previousDocument() => void
nextDocument() => void
returnsReactElement<any, any> | null

ITheme

nametype
primary?string
secondary?string
tertiary?string
text_primary?string
text_secondary?string
text_tertiary?string
disableThemeScrollbar?boolean

DocRenderer extends React.FC\<DocRendererProps>

nametype
fileTypesstring[]
weightnumber
fileLoader?FileLoaderFunction | null | undefined

FileLoaderFunction

(props: FileLoaderFuncProps) => 空白


FileLoaderFuncProps

nametype
documentURIstring
signalAbortSignal
fileLoaderCompleteFileLoaderComplete

FileLoaderComplete

nametype
fileReaderFileReader

DocRendererProps

nametype
mainStateIMainState

IMainState

nametype
currentFileNonumber
documentsIDocument[]
documentLoading?boolean
currentDocument?IDocument
rendererRect?DOMRect
config?IConfig

react-doc-viewer

Contents



Current Renderable File Types

ExtensionMIME TypeAvailable
bmpimage/bmp
docapplication/msword
docxapplication/vnd.openxmlformats-officedocument.wordprocessingml.document
htmtext/htm
htmltext/html
jpgimage/jpg
jpegimage/jpeg
pdfapplication/pdf
pngimage/png
pptapplication/vnd.ms-powerpoint
pptxapplicatiapplication/vnd.openxmlformats-officedocument.presentationml.presentation
tiffimage/tiff
txttext/plain
xlsapplication/vnd.ms-excel
xlsxapplication/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

nametype
documentsIDocument[]
className?string
style?React.CSSProperties
config?IConfig
theme?ITheme
pluginRenderers?DocRenderer[]

IDocument

nametype
uristring
fileType?string
fileData?string | ArrayBuffer - Used Internally - Ignored if passed into props

IConfig

nametype
header?IHeaderConfig

IHeaderConfig

nametype
disableHeader?boolean
disableFileName?boolean
retainURLParams?boolean
overrideComponent?IHeaderOverride

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

nametype
stateIMainState
previousDocument() => void
nextDocument() => void
returnsReactElement<any, any> | null

ITheme

nametype
primary?string
secondary?string
tertiary?string
text_primary?string
text_secondary?string
text_tertiary?string
disableThemeScrollbar?boolean

DocRenderer extends React.FC\<DocRendererProps>

nametype
fileTypesstring[]
weightnumber
fileLoader?FileLoaderFunction | null | undefined

FileLoaderFunction

(props: FileLoaderFuncProps) => void


FileLoaderFuncProps

nametype
documentURIstring
signalAbortSignal
fileLoaderCompleteFileLoaderComplete

FileLoaderComplete

nametype
fileReaderFileReader

DocRendererProps

nametype
mainStateIMainState

IMainState

nametype
currentFileNonumber
documentsIDocument[]
documentLoading?boolean
currentDocument?IDocument
rendererRect?DOMRect
config?IConfig

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文