Skip to Content
AnyPreview

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.

<DocViewer> is built from public pieces. useDocViewer gives you a controller: the document's state (loading progress, page, zoom, search results, outline) and commands (go to a page, zoom, search, print). <DocumentSurface> draws the document. Everything else, such as buttons, inputs, panels and layout, is yours. Use shadcn/ui, MUI, Mantine or your own design system.

You wantUse
A complete viewer<DocViewer>
The stock viewer with one part replacedslots
Your own controls around the documentuseDocViewer + <DocumentSurface> (this page)

Quick start

import { DocumentSurface, useDocViewer } from '@anypreview/react';
import '@anypreview/react/styles.css';

export function MyViewer({ file }: { file: File }) {
  const viewer = useDocViewer({ source: file });

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: 600 }}>
      <header>
        <button onClick={viewer.prev}>Back</button>
        {viewer.page} / {viewer.pageCount}
        <button onClick={viewer.next}>Next</button>
        <button onClick={viewer.zoomIn}>{Math.round(viewer.scale * 100)}%</button>
      </header>
      <DocumentSurface viewer={viewer} style={{ flex: 1, minHeight: 0 }} />
    </div>
  );
}

Three rules:

  1. Render <DocumentSurface viewer={viewer}> once. It loads the right renderer and draws the document. Without it, the controller has nothing to control.
  2. Give the surface a height. It fills its box and scrolls inside it.
  3. Read before you act. Every format supports a different set of commands; viewer.can says which (see What each format supports). Commands that don't apply do nothing, so calling them is safe, but showing their buttons would confuse readers.

useDocViewer takes the same options as <DocViewer> (source, fileName, theme, defaultZoom, password, rememberPosition, messages, locale, pdf, html, the on… callbacks and the rest; see Usage), except the layout props toolbar, className, style and slots.

The life of a document

viewer.status moves through these values. Each one is a chance to show your own UI.

statusWhat is happeningUseful state
'loading'Bytes are being read or downloaded.progress.loaded, progress.total (when the server sends a length)
'locked'A password-protected Word, Excel or PowerPoint file is waiting for its password. The surface shows the password prompt; pass the password option to skip it.fileName, detection
'ready'The file is identified and being drawn. Page, zoom, outline and the other state fill in as the renderer reports them.everything
'error'The file could not be read or drawn.error.message

Protected PDFs are different: they reach 'ready' and pdf.js asks for the password inside the surface.

examples/headless/states.tsx
'use client';
// Every state a document goes through, with your own UI for each. The surface still draws the
// password prompt for protected files (status 'locked'); pass `password` to skip it.
import { DocumentSurface, formatBytes, useDocViewer, type DocSource } from '@anypreview/react';
import '@anypreview/react/styles.css';

export default function StatefulViewer({ source }: { source: DocSource }) {
  const viewer = useDocViewer({
    source,
    onLoad: ({ detection, byteLength }) => console.log(`opened ${detection.ext}, ${byteLength} bytes`),
    onError: (error) => console.warn('could not open', error),
  });

  let banner: string | undefined;
  switch (viewer.status) {
    case 'loading':
      banner = viewer.progress.total
        ? `Downloading… ${Math.round((viewer.progress.loaded / viewer.progress.total) * 100)}%`
        : `Downloading… ${formatBytes(viewer.progress.loaded)}`;
      break;
    case 'locked':
      banner = 'This file is protected. Enter its password below.';
      break;
    case 'error':
      banner = `Could not open this file: ${viewer.error?.message}`;
      break;
    case 'ready':
      banner = `${viewer.fileName ?? 'Document'}: ${viewer.detection?.mime} (${viewer.detection?.confidence} match)`;
      break;
  }

  return (
    <div className="flex h-full flex-col text-sm">
      <p role="status" className="border-b p-2">{banner}</p>
      <DocumentSurface viewer={viewer} className="min-h-0 flex-1" />
    </div>
  );
}
Live: the example above, built only with the public hooks, running on report.docx.

State reference

The document

Prop

Type

Position and view

Prop

Type

What the open file supports

viewer.can is recomputed for each file. Use it to show or hide controls.

Prop

Type

Prop

Type

Prop

Type

Interface

Prop

Type

Commands reference

All commands are stable functions: safe in dependency arrays and as event handlers.

Prop

Type

Hooks and components

Prop

Type

What each format supports

What the controller reports for each format. ✓ means the matching can flag is true or the state is filled in.

FormatpageKindpageCount countsZoomFitRotateSearchThumbnailsOutline from
PDFpagepages✓✓✓✓✓bookmarks
Word, ODTpagelaid-out pages✓✓✓✓headings
PowerPoint, ODPslideslides✓✓✓✓slide titles
Excel, ODSsheetvisible sheets✓✓
CSV, TSV, JSON, XML0✓✓
Code, text, logs0✓✓
Markdown, notebooks0✓✓headings
Images, SVG0✓✓✓
TIFFpagepages✓✓✓✓
Email, ZIP0✓
HTML0✓
Audio, video0

Print and download work for every format once it is ready. Each format page has a live inspector of these values and a headless example built for it.

One toolbar for every format

Drive your controls from can, pageCount and pageKind, and the same component suits every file:

examples/headless/adaptive.tsx
'use client';
// One toolbar for every format: each control appears only when the open file supports it,
// read from `viewer.can`, `pageCount`, `pageKind`, `outline` and `thumbnails`.
import { useState } from 'react';
import { DocumentSurface, useDocViewer, useDocumentSearch, type DocSource } from '@anypreview/react';
import '@anypreview/react/styles.css';

export default function AdaptiveViewer({ source }: { source: DocSource }) {
  const viewer = useDocViewer({ source });
  const [query, setQuery] = useState('');
  const results = useDocumentSearch(viewer, query);
  const { can } = viewer;

  return (
    <div className="flex h-full flex-col text-sm" onKeyDown={viewer.onKeyDown}>
      <header className="flex flex-wrap items-center gap-2 border-b p-2">
        {viewer.pageCount > 1 && (
          <span>
            <button onClick={viewer.prev}>‹</button> {viewer.pageKind} {viewer.page} / {viewer.pageCount} <button onClick={viewer.next}>›</button>
          </span>
        )}
        {can.zoom && (
          <span>
            <button onClick={viewer.zoomOut}>−</button> {Math.round(viewer.scale * 100)}% <button onClick={viewer.zoomIn}>+</button>
          </span>
        )}
        {can.fit && <button onClick={() => viewer.setZoom('fit-width')}>Fit width</button>}
        {can.rotate && <button onClick={viewer.rotate}>Rotate</button>}
        {can.search && <input className="rounded border px-2" placeholder="Search" value={query} onChange={(e) => setQuery(e.target.value)} />}
        {query && <span>{results.count} found</span>}
        {can.sidebar && <button onClick={() => viewer.toggleSidebar()}>{viewer.sidebar.open ? 'Hide' : 'Show'} panel</button>}
        <span className="ml-auto" />
        {can.print && <button onClick={() => void viewer.print()}>Print</button>}
        {can.download && <button onClick={viewer.download}>Download</button>}
      </header>
      <DocumentSurface viewer={viewer} className="min-h-0 flex-1" />
    </div>
  );
}
Live: the example above, built only with the public hooks, running on slides.pptx.

Replacing one part of the stock viewer

To swap one piece of <DocViewer>, use slots instead of going fully headless. Each slot gets the same controller:

<DocViewer
  source={file}
  slots={{
    toolbar: (viewer) => <MyToolbar viewer={viewer} />,
    loading: (viewer) => <MySpinner percent={viewer.progress.total ? viewer.progress.loaded / viewer.progress.total : undefined} />,
    sidebar: () => null, // no side panel
  }}
/>

On this page