Skip to Content
AnyPreview

PDF

Show PDF files in React with pdf.js in a Web Worker, selectable text, search, bookmarks, password prompts and smooth scrolling through 1,000-page documents.

PDFs are drawn by pdf.js, the engine inside Firefox, running in a Web Worker.

Live: report.pdf rendered by the library in this page.Open in the playground

Supported

  • Selectable and searchable text, with search covering every page from a background index.
  • Bookmarks as the outline, page thumbnails, links inside and out of the document.
  • Encrypted files: the viewer asks for the password, or uses the password prop.
  • Zoom, fit to width or page, rotation, and printing every page at about 190 dpi, form fields included.

Long documents

Only pages within about a screen of the view are drawn, and pages that scroll far away release their memory. Every page keeps its real size, so the scroll bar is accurate and jumping to any page is immediate.

Live: a 500-page PDF.Open in the playground

Setup

Serve the pdf.js assets and pass pdf={{ assetsUrl }}. See Installation. For strict CSPs or unusual bundlers, pdf.createWorker lets you supply the worker.

Controller

What useDocViewer reports while a PDF is open:

StateFor a PDF
pageKind, page, pageCount'page', the page most in view, and the number of pages.
zoom, scaleEvery zoom works, fit modes included. scale is the size shown, so fit-width on a wide window may be 1.4.
rotation0, 90, 180 or 270; rotates every page.
outlineThe PDF's bookmarks, nested as in the file. goToOutline jumps to the bookmark's exact position, not just its page. Empty when the PDF has none.
thumbnailsOne per page, drawn by pdf.js at thumbnail size.
search.countMatches across all pages, from a background text index, so pages not drawn yet are counted too.
canAll true: zoom, fit, rotate, search, print, download, sidebar.
Live: useDocViewer on report.pdf. Press a command and watch the state change.

Things to know:

  • goTo(n) on a long PDF is immediate: every page keeps its real size, so the target page is scrolled to and drawn.
  • findNext() reaches matches on pages that are not drawn yet; they are drawn as it scrolls there.
  • print() re-renders every page for paper, so it can take a few seconds on long files: show printing.
  • Encrypted PDFs reach status: 'ready', and pdf.js asks for the password inside the surface. Pass password to skip the prompt.

Headless

A reader with a page box, zoom and fit, rotation, search, printing, and a side panel with thumbnails and bookmarks:

examples/headless/pdf.tsx
'use client';
// A PDF reader: page box, zoom and fit, rotation, search, print, and a side panel with page
// thumbnails and the PDF's bookmarks.
import { useState } from 'react';
import { DocumentSurface, Thumbnail, useDocViewer, useDocumentSearch, useOutline, useThumbnails, type DocSource, type OutlineItem } from '@anypreview/react';
import '@anypreview/react/styles.css';

export default function PdfReader({ source }: { source: DocSource }) {
  const viewer = useDocViewer({ source, defaultZoom: 'fit-width', pdf: { assetsUrl: '/pdfjs/' } });
  const thumbs = useThumbnails(viewer);
  const bookmarks = useOutline(viewer);
  const [panel, setPanel] = useState<'pages' | 'bookmarks'>('pages');
  const [query, setQuery] = useState('');
  const results = useDocumentSearch(viewer, query);

  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">
        <button onClick={viewer.prev} disabled={(viewer.page ?? 1) <= 1}>Previous</button>
        <input
          aria-label="Page"
          className="w-12 rounded border px-1 text-center"
          value={viewer.page ?? ''}
          onChange={(e) => viewer.goTo(Number(e.target.value))}
        />
        <span>of {viewer.pageCount}</span>
        <button onClick={viewer.next} disabled={(viewer.page ?? 1) >= viewer.pageCount}>Next</button>
        <span className="mx-2">|</span>
        <button onClick={viewer.zoomOut}>−</button>
        <span>{Math.round(viewer.scale * 100)}%</span>
        <button onClick={viewer.zoomIn}>+</button>
        <button onClick={() => viewer.setZoom('fit-width')}>Fit width</button>
        <button onClick={() => viewer.setZoom('fit-page')}>Fit page</button>
        <button onClick={viewer.rotate}>Rotate ({viewer.rotation}°)</button>
        <input className="ml-auto rounded border px-2" placeholder="Search" value={query} onChange={(e) => setQuery(e.target.value)} />
        {query && (
          <span>
            {results.count ? `${results.current + 1} of ${results.count}` : 'No matches'}
            <button onClick={results.prev}>↑</button>
            <button onClick={results.next}>↓</button>
          </span>
        )}
        <button onClick={() => void viewer.print()} disabled={viewer.printing}>Print</button>
      </header>

      <div className="flex min-h-0 flex-1">
        <nav className="w-44 shrink-0 overflow-y-auto border-r p-2">
          <div className="mb-2 flex gap-2">
            <button aria-pressed={panel === 'pages'} onClick={() => setPanel('pages')}>Pages</button>
            {bookmarks.length > 0 && <button aria-pressed={panel === 'bookmarks'} onClick={() => setPanel('bookmarks')}>Bookmarks</button>}
          </div>
          {panel === 'pages' && thumbs
            ? Array.from({ length: thumbs.count }, (_, i) => (
                <button key={i} className="mb-2 block" aria-current={viewer.page === i + 1 || undefined} onClick={() => viewer.goTo(i + 1)}>
                  <Thumbnail viewer={viewer} index={i} width={120} />
                  {i + 1}
                </button>
              ))
            : <Bookmarks items={bookmarks} onPick={viewer.goToOutline} />}
        </nav>
        <DocumentSurface viewer={viewer} className="min-w-0 flex-1" />
      </div>
    </div>
  );
}

function Bookmarks({ items, onPick }: { items: OutlineItem[]; onPick: (item: OutlineItem) => void }) {
  return (
    <ul className="pl-2">
      {items.map((item, i) => (
        <li key={i}>
          <button className="text-left" onClick={() => onPick(item)}>{item.title}</button>
          {item.items?.length ? <Bookmarks items={item.items} onPick={onPick} /> : null}
        </li>
      ))}
    </ul>
  );
}
Live: the example above, built only with the public hooks, running on report.pdf.

Not yet

  • Filling in forms. Form fields are shown, not edited.

On this page