GithubHelp home page GithubHelp logo

react-doc-viewer's Introduction

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

react-doc-viewer's People

Contributors

hawekotte avatar mattmogford avatar mattmogford-alcumus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

react-doc-viewer's Issues

File Not Found for .docx file types

image

All other file types can be viewed and working fine except docx

<DocViewer documents={initVal} pluginRenderers={DocViewerRenderers} style={{width:"100%", minHeight:"600px", marginBottom:"30px"}} />

All files are from firebase storage which is already enabled CORS

Demo

Is there an online demo somewhere? Thanks!

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons

Hi! I tried to use react-doc-viwer in my react project, but I come across on this issue:

Screenshot from 2021-03-11 00-34-23

I tried to change versions of react, adding separate react in peerDependencies.
react-doc-viwer use [email protected] and [email protected] so in theory it support hooks. If it's not problem with : Mismatching Versions of React and React DOM , I don't know what is going on...

paskage.json

 {
  "name": "trainings",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@ckeditor/ckeditor5-build-classic": "^26.0.0",
    "@ckeditor/ckeditor5-build-decoupled-document": "^26.0.0",
    "@ckeditor/ckeditor5-react": "^3.0.1",
    "@testing-library/jest-dom": "^5.11.9",
    "@testing-library/react": "^11.2.5",
    "@testing-library/user-event": "^12.8.1",
    "jquery": "^3.6.0",
    "react-doc-viewer": "^0.1.5",
    "react-movable": "^2.5.3",
    "react-redux": "^7.2.2",
    "react-scripts": "4.0.3",
    "redux": "^4.0.5",
    "semantic-ui-css": "^2.4.1",
    "semantic-ui-react": "^2.0.3",
    "web-vitals": "^1.1.0"
  },
  "peerDependencies": {
    "react": "^17.0.1",
    "react-dom": "^17.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

My function to render was just simply copied from the example.

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} />;
}

doc-nav previous n next not working

at initial 1st file of documents[] loads but after using doc-nav previous or next button. loader keeps on loading bcoz fetch request is not made to 2nd file

Could you support content-type to determine URL validity?

I'm storing images in firebase. These end up with a format like this:

https://firebasestorage.googleapis.com/v0/b/graceblocks-4efeb.appspot.com/o/customers%2Fschema_1%2Fattachments%2F67282db5-5a8c-4d66-9862-968ce6fcecf3.jpg?alt=media&token=35f685d8-c449-42cc-bafe-cc70e44370e5

The DocViewer doesn't recognize this URL as a .JPG even though it is. Is there anyway to add support where we specify the content-type of the URL instead of relying on the extension itself?

ERROR in ./node_modules/react-pdf/dist/esm/eventBus.js

Hi, I am getting this error when I am using the package on my rails react app,

"export 'EventBus' was not found in 'pdfjs-dist/lib/web/ui_utils'

It's a simple import not anything fancy

import DocViewer from "react-doc-viewer";

const docs = [
    { uri: "http://www.orimi.com/pdf-test.pdf" },
  ];
  
  <DocViewer documents={docs} />

Would appreciate any help on this.

My rails version is 5.2.3
My react version is 16.3.0
My node version is 13.7.0

I am using yarn instead of npm as it goes with my project. Using webpack to compile the JS.

Thanks

Excel,Docs Files Not supported in Base64 Input method

Hi Team,

I try to load the files using the Base64 method. such as below

<DocViewer
documents={[{uri: this.state.FileBase64}]}
pluginRenderers={DocViewerRenderers} config={{header:{ disableHeader: true,
disableFileName:true}}}/>

Its working fine for PDF and Images but not working for Docx,doc,xlsx files.

image

please help me to fix this issue

Hide controls

Is it possible to hide the header controls( Zoom, Pagination, download, etc), or can I move it to the bottom?

Duplicate File loading

  • Don't initially download the whole file, just fetch the headers and determine the mime-type
  • If a custom renderer needs to load the file itself, add a callback function to run after the mime-type is detected

Docx is not working

Hello,
i am trying to show docx type document but it showing error.
Screenshot 2021-02-12 194148

for this is used code
const docs = [
{ uri: "http://localhost:8080/UploadDocs/sampleDoc.docx" },
{ uri: "http://localhost:8080/UploadDocs/sampleformat1032.rtf" },
{ uri: "http://localhost:8080/UploadDocs/sapmle123.txt" },
{ uri: "http://localhost:8080/UploadDocs/143.pdf" }
// { uri: require("D:/Apache Software Foundation/Tomcat 8.5/webapps/UploadDocs/143.pdf") }, // Local File
];
return (

);

please correct me if wrong or please give solution on it

HTML Renderer not working

I'm getting below error.

scheduler.development.js:171 Uncaught DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.
    at http://localhost:8888/static/js/6.chunk.js:197230:23

For htm file below:

<!DOCTYPE html>
<html>
	<body>
		<div style="width: 500px; margin: auto">
			<h2>Some Display for Lennox</h2>
			<div>Rating: <span id="rb-rating">0</span></div>
			<div>Total Reviews: <span id="rb-reviews-total">0</span></div>
		</div>

		<div style="margin-top: 100px">
			<script
				type="text/javascript"
				src="https://public.staging.rbfeedback.com/widget/expanded/5c627211ad3270412a47f5a3?testimonials=1"
				async
			></script>
		</div>
	</body>
</html>

Recoil as an experiment went very well, but should be retired until it has RC

Recoil is a Facebook experiment to overcome issues with redux, react contexts and states.
Although, looks like it won't have a Release Candidate very soon.
But definitely will be something to look at in the future.

Revert to style of React Context and useReducer from just before features/recoil was merged in.
The data structures etc. will most likely need altering at this point so it won't just be a simple rollback.

No Renderer for file type application/octet-stream

Getting this error when i try to view pptx or docx files.

import React from 'react'
import { useRouteMatch } from "react-router-dom";
import DocViewer, { MSDocRenderer } from "react-doc-viewer";

const Document = (props) => {
  const match = useRouteMatch();

  const docs = [
    { uri: "https://queue.nyc3.cdn.digitaloceanspaces.com/lkfjslkdfj.pptx" }
  ];

  return(
    <React.Fragment>
      Document.js
      <DocViewer documents={docs} pluginRenderers={[MSDocRenderer]} />
    </React.Fragment>
  )
}

export default Document; 
// https://queue.nyc3.cdn.digitaloceanspaces.com/agency%20reachout%20.docx
// https://queue.nyc3.cdn.digitaloceanspaces.com/lkfjslkdfj.pptx

Page Navigation

Hi, thanks for your work.

Could you add parameters for page number/navigation, so the user can pass a page number to open the specified page.

Add AUTH headers to Doc Uri?

I am wanting to use the document URI to display a file, but I cant seem to figure out how to add custom headers to the Head and Get http calls that happen.

These headers are things so that the requests can be authenticated.

I tried converting the file into a blob Uri, but I get method not accepted.

CORS Issues

Hi,
Thanks for this usefull package.

I'm wondering about how I can add the credentials to the fetch request.
This crendentials are needed as we must be logged to have the rights access.

For the time being, I updated directly the code of fileLoader.js :
from
return fetch(documentURI, { signal: signal })
to
return fetch(documentURI, { signal: signal, credentials: 'include' })

Is there another solution to solve this issue ?

Thanks in advance

CORS Policy Issue

Hi,

I'm getting Access to fetch at 'https://remote_server/sample.pdf' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. while loading a remote file.

How do I resolve this on react-doc-viewer?

Thanks

.jg files stuck in loading

Hi,

Firstly, thanks for taking the time to create such a great package.

Images loading from the filesystem work great. But I'm having some issues loading .jpg files from the host URL. Something like: api.localhost.com/img.jpg . React-doc-viewer just sits there spinning. I can, however, view the image fine if I encapsulate it in a html tag <img src="api.localhost.com/img.jpg"/> so I know the link is good.

I was wondering if perhaps my webpack settings might be affecting the behaviour of react-file-viewer? I've atttached a snippet below. Do you see any possible issues?

{
       test: /\.(jpg|png|mp4|mp3)$/, 
          use: {
            loader: "url-loader",
            options: {
              name: "[path][name].[ext]",
              publicPath: "/",
            },
          },
}

I'm using "react-doc-viewer": "^0.1.5" with Typescript (es5) and "react": "^16.13.1".
Any tips to debug would be much appreciated!

Cheers

Same file type toggle

I found an issue by using previous et and next function.

If 2 files have the same file type, the next file is not uploading and it's loading infinity.

I would like to help you on this package, don't hesitate if you need another hand.

Thank you again for developing this package !

add option for view files tif

Add option for view files tif, this library or extesion is the most complete that I found, and I do testing to integrate this with my web app, the option for view docs, no works

No Renderer for file type application/vnd.openxmlformats-officedocument.wordprocessingml.document

Hello!

I am getting this message when I try to use this library:

image

This is my code:

Am I doing anything wrong? Thanks in advance for your answer!

import React from 'react'
import DocViewer from 'react-doc-viewer'

function Viewer() {

// const path = './Sample1.docx'

const docs = [
// { uri: path }, // Local File
{ uri: require('./Interview.docx') }, // Local File
]

return (

)
}

export default Viewer

Make all ui replaceable through component props

Make individual UI elements replaceable.
E.g. fileName, document controls and the whole header.
Document controls override prop should return a function that provides callbacks to prev and next document navigation.

PDFRenderer error: Can't perform a React state update on an unmounted component

Hi, I get the following error message which causes the PDF page viewer UI to collapse. It happens when the component is re-rendered which is triggered via a React state update. It seems that the error originates from PDFRenderer plugin component.

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
    in Document (created by Styled(Document))
    in Styled(Document) (created by PDFPages)
    in PDFPages (created by PDFRenderer)
    in div (created by styled.div)
    in styled.div (created by PDFRenderer)
    in PDFProvider (created by PDFRenderer)
    in PDFRenderer (created by Contents)
    in Contents

I'm able to reproduce this issue in my code sandbox - (https://codesandbox.io/s/affectionate-feistel-zpfhn). Ignore Failed to load PDF file error. Codesandbox doesn't support loading a PDF file from an external source.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.