Usage
Open files, bytes and URLs with DocViewer, set its options, react to its events and control it from your code.
Sources
source takes whatever you have. Keep the value stable between renders (useMemo or state), because a new value opens the file again.
<DocViewer source={file} /> // File or Blob, e.g. from <input type="file">
<DocViewer source={bytes} fileName="report.docx" /> // ArrayBuffer or Uint8Array
<DocViewer source="https://example.com/a.pdf" /> // URL; the server must allow CORS
<DocViewer source={{ url, headers: { Authorization: `Bearer ${token}` }, credentials: 'include' }} />The type is detected from the file's bytes, so a missing or wrong extension does not matter. Pass fileName or mimeType as hints when the bytes alone are ambiguous (plain text, for example), or type to skip detection. See Detection.
Props
Prop
Type
Events
Prop
Type
Controlling the viewer from your code
import { useRef } from 'react';
import { DocViewer, type DocViewerHandle } from '@anypreview/react';
function Reader({ file }: { file: File }) {
const viewer = useRef<DocViewerHandle>(null);
return (
<>
<button onClick={() => viewer.current?.goTo(1)}>First page</button>
<button onClick={() => viewer.current?.search('total')}>Find “total”</button>
<button onClick={() => void viewer.current?.print()}>Print</button>
<DocViewer ref={viewer} source={file} />
</>
);
}The handle has goTo, next, prev, setZoom, zoomIn, zoomOut, rotate, download, print, search(query, { matchCase, wholeWord }) (returns the match count), findNext, findPrev, clearSearch, toggleSidebar(open?, tab?), goToOutline(item) and getState().
Keyboard
| Keys | Action |
|---|---|
| Ctrl/⌘ + F | Search; Enter and Shift+Enter (or F3) move between matches, Esc closes |
| Page Up / Page Down, Home / End | Previous or next page, first or last page |
| Ctrl/⌘ + 0 | Reset zoom |
| Ctrl/⌘ + P | Print the document, not the page around it |
| Arrow keys | Scroll; in spreadsheets, move between cells |
Installation
Install @anypreview/react, import its stylesheet and serve the pdf.js assets. Setup notes for Vite, Next.js and strict Content Security Policies.
Headless hooks
Build your own toolbar, search, sidebar or whole viewer with useDocViewer. Full reference of the controller's state and commands, what each format supports, and live examples.