mantine-doc-viewer

Document viewer for Mantine: PDF, images, text, code and markdown

Installation

yarn add mantine-doc-viewer @mantine/core @mantine/hooks @mantine/code-highlight

mantine-doc-viewer has no dependency on a PDF or markdown library. The engines that show those files are optional peer dependencies that your app installs and hands to the viewer through adapters, as @mantine/code-highlight does for syntax highlighters. Install what the files you show need:

  • pdfjs-dist to show PDF files
  • react-markdown and remark-gfm to render markdown files
  • @cantoo/pdf-lib for mantine-doc-viewer/editor, which writes page rotations into a PDF; the markup extension does not need it
yarn add pdfjs-dist react-markdown remark-gfm @cantoo/pdf-lib

After installation import package styles at the root of your application:

import '@mantine/core/styles.css';
import '@mantine/code-highlight/styles.css';
import 'mantine-doc-viewer/styles.css';

The one styles.css covers the whole package, including mantine-doc-viewer/editor and mantine-doc-viewer/markup. Skip the @mantine/code-highlight import if you do not show code.

Usage

DocViewer shows a PDF, image, plain text, code or markdown file from its src. The document type is detected from mimeType, fileName or the extension of src. Wrap your app in MantineProvider, and in DocViewerAdapterProvider with the engines you installed; see Adapters below for each of them:

import '@mantine/core/styles.css';
import '@mantine/code-highlight/styles.css';
import 'mantine-doc-viewer/styles.css';

import { MantineProvider } from '@mantine/core';
import { createPdfJsAdapter, DocViewer, DocViewerAdapterProvider } from 'mantine-doc-viewer';
import workerSrc from 'pdfjs-dist/build/pdf.worker.min.mjs?url';

const pdf = createPdfJsAdapter(() => import('pdfjs-dist'), { workerSrc });

function Demo() {
  return (
    <MantineProvider>
      <DocViewerAdapterProvider pdf={pdf}>
        <DocViewer src="/files/report.pdf" h={500} />
      </DocViewerAdapterProvider>
    </MantineProvider>
  );
}

Give the viewer a height with the h prop or from its parent: documents are scrolled and fitted inside the viewer, they do not make it grow. The demos on this page assume the providers above are mounted at the root of the page:

sample.pdf
Loading document
import { DocViewer } from 'mantine-doc-viewer';

function Demo() {
  return <DocViewer src="/sample.pdf" h={500} />;
}

Adapters

PDF files are drawn with pdf.js. createPdfJsAdapter takes a function that imports pdfjs-dist, so pdf.js is downloaded only when a PDF is opened, and the url of the pdf.js worker from the same pdfjs-dist version. Without workerSrc the adapter throws an error that names the missing worker, unless your app set GlobalWorkerOptions.workerSrc itself:

// Vite
import workerSrc from 'pdfjs-dist/build/pdf.worker.min.mjs?url';

// Next.js, webpack 5 and other bundlers that support new URL()
const workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString();

The options of createPdfJsAdapter are passed to pdf.js getDocument, for example password, withCredentials, httpHeaders, cMapUrl or disableRange for signed storage urls that do not support range requests. Set standardFontDataUrl (the standard_fonts folder of pdfjs-dist) and useSystemFonts: false so PDFs that do not embed the standard 14 fonts render the same on every system, without pdf.js font warnings in the console. Pass a function to set them per document:

import { createPdfJsAdapter } from 'mantine-doc-viewer';

const pdf = createPdfJsAdapter(() => import('pdfjs-dist'), {
  workerSrc,
  options: (src) => ({ withCredentials: src.startsWith('/api/'), disableRange: true }),
});

Markdown files are rendered with react-markdown and remark-gfm through createReactMarkdownAdapter, which takes a function that imports both. Raw HTML in the file is not rendered, so untrusted files are safe to preview, and relative links and images are resolved against the url of the markdown file. The adapters are optional: without the PDF adapter a PDF shows a message with a download link, and without the markdown adapter a markdown file shows its source.

import { createReactMarkdownAdapter, DocViewerAdapterProvider } from 'mantine-doc-viewer';

const markdown = createReactMarkdownAdapter(() =>
  Promise.all([import('react-markdown'), import('remark-gfm')])
);

<DocViewerAdapterProvider pdf={pdf} markdown={markdown}>
  {children}
</DocViewerAdapterProvider>;

Create the adapters once, outside of components, and nest providers to use different engines in one part of the app. Toggle the markdown adapter in the demo to see the fallback:

sample.md
Loading document
import { SegmentedControl, Stack } from '@mantine/core';
import {
  createPdfJsAdapter,
  createReactMarkdownAdapter,
  DocViewer,
  DocViewerAdapterProvider,
} from 'mantine-doc-viewer';

const workerSrc = new URL('pdfjs-dist/build/pdf.worker.min.mjs', import.meta.url).toString();
const pdf = createPdfJsAdapter(() => import('pdfjs-dist'), { workerSrc });
const markdown = createReactMarkdownAdapter(() =>
  Promise.all([import('react-markdown'), import('remark-gfm')])
);

function Demo() {
  const [engine, setEngine] = useState('markdown');

  return (
    <Stack>
      <SegmentedControl
        value={engine}
        onChange={setEngine}
        data={[
          { label: 'With the markdown adapter', value: 'markdown' },
          { label: 'Without it', value: 'none' },
        ]}
      />
      <DocViewerAdapterProvider pdf={pdf} markdown={engine === 'markdown' ? markdown : undefined}>
        <DocViewer src="/sample.md" h={400} />
      </DocViewerAdapterProvider>
    </Stack>
  );
}

Code and JSON are highlighted by CodeHighlight from @mantine/code-highlight, so colors come from the highlighting adapter of your app, the same setup as for CodeHighlight itself.

Document types

DocViewer picks the view from the type of the document, and a toolbar that matches it. Set type when the url has no extension, for example a signed download link.

  • PDF pages with search, thumbnails, an outline, page layouts, rotation, document info and a presentation mode
  • Image fitted to the viewer, never enlarged past its natural size, with zoom around the pointer and rotation
  • Plain text in a monospace font, with a toggle for line wrapping
  • Code with CodeHighlight. The language is detected from the file extension, language of DocViewer.Code overrides it
  • JSON as a collapsible tree when it is valid, with a switch to the code
  • Markdown rendered with GitHub flavored markdown, with a switch to the source

Text, code and markdown files are downloaded with fetch, so src must allow it (same origin or CORS). Files larger than maxSize bytes (2 MB by default) are not loaded, and a download link is shown instead. Pick a file in the demo:

sample.pdf
Loading document
import { SegmentedControl, Stack } from '@mantine/core';
import { DocViewer } from 'mantine-doc-viewer';

const files = [
  { label: 'PDF', value: '/sample.pdf' },
  { label: 'Image', value: '/sample-image.svg' },
  { label: 'Markdown', value: '/sample.md' },
  { label: 'JSON', value: '/sample.json' },
  { label: 'Code', value: '/sample.ts' },
  { label: 'Text', value: '/sample.csv' },
];

function Demo() {
  const [src, setSrc] = useState(files[0].value);

  return (
    <Stack>
      <SegmentedControl data={files} value={src} onChange={setSrc} />
      <DocViewer src={src} h={420} />
    </Stack>
  );
}

keepView keeps the zoom, rotation, page layout and scroll position when src changes to another document of the same type, for example with a next button. Search, page edits and the loaded document itself still reset. Without it, a new src starts the viewer afresh.

Compound components

DocViewer is DocViewer.Root with a default layout for the type of the document. To change the layout, use DocViewer.Root and the parts, like Lightbox.Root and its parts. DocViewer.Root takes the file, the Styles API props, labels, the store and the state of the viewer, and shares them with its parts. Parts must be rendered inside DocViewer.Root, and each is also available as a named export such as DocViewerToolbar.

PartRenders
DocViewer.ToolbarToolbar, with the default controls of the document type when it has no children
DocViewer.SearchSearch bar of a PDF, opened by the search button or Ctrl or Cmd and F
DocViewer.MainRow under the toolbar: thumbnails and pages of a PDF by default
DocViewer.ThumbnailsPage thumbnails of a PDF, shown while they are opened
DocViewer.PagesScrollable PDF pages, with events for links, text selection and reading progress
DocViewer.ImageImage with zoom, rotation and panning
DocViewer.TextPlain text file, wrapped or not
DocViewer.CodeCode and JSON files
DocViewer.MarkdownMarkdown file, rendered or as source
DocViewer.BodyScrollable area for your own view
DocViewer.MessageMessage in the area of the document, for errors and empty states
DocViewer.LoadingLoading indicator
DocViewer.OverlayControlsZoom and full screen buttons over the document
DocViewer.PresentationControlsPage count and exit button of a presentation

The toolbar controls, Outline, DocumentInfo and the other parts are listed in the sections that use them. The demo below puts the default layout of a PDF together from its parts, with thumbnails at 96px and wide gaps between pages:

sample.pdf
Loading document
import { DocViewer } from 'mantine-doc-viewer';

function Demo() {
  return (
    <DocViewer.Root src="/sample.pdf" defaultThumbnailsOpened h={500}>
      <DocViewer.Toolbar />
      <DocViewer.Search />
      <DocViewer.Main>
        <DocViewer.Thumbnails width={96} />
        <DocViewer.Pages gap="xl" />
      </DocViewer.Main>
    </DocViewer.Root>
  );
}

DocViewer also takes children, which replace the default layout, and a few props that reach the default parts without writing the layout: withToolbar, toolbarControls, toolbarProps, withOverlayControls, pagesProps, thumbnailsProps, searchProps, imageProps and textProps.

Toolbar and controls

DocViewer.Toolbar without children renders the controls of the document type. Pass children to choose and order the controls yourself. Every control is a part: Title, PageControls, ZoomControls, ThumbnailsButton, RotateButton, LayoutMenu, OutlineButton, InfoButton, PresentationButton, SearchButton, PrintButton, DownloadButton, FullscreenButton, WrapButton and ViewModeControl. Controls that do nothing for the document, such as the page controls of an image, render nothing, so one toolbar can serve every file type.

sample.pdfDraft 4
Loading document
import { DocViewer } from 'mantine-doc-viewer';

function Demo() {
  return (
    <DocViewer.Root src="/sample.pdf" size="sm" h={500}>
      <DocViewer.Toolbar subtitle="Draft 4">
        <DocViewer.PageControls />
        <DocViewer.ZoomControls />
        <DocViewer.SearchButton />
        <DocViewer.DownloadButton />
      </DocViewer.Toolbar>
      <DocViewer.Search />
      <DocViewer.Main />
    </DocViewer.Root>
  );
}

leftSection puts content before the title, rightSection after the document controls, and title and subtitle replace the file name and add a small line under it. The default toolbar also takes controls to hide controls without writing the toolbar, and so does DocViewer as toolbarControls. Hidden controls' keyboard shortcuts still work, and the store still has their actions. toggleOnTap hides and shows the toolbar when a finger taps the viewer, so a page can fill a phone, and tooltipProps reach every tooltip in the toolbar.

withOverlayControls floats zoom and full screen buttons over the top right of the document, for a viewer without a toolbar, and DocViewer.OverlayControls does the same in a custom layout. Both leave out a control that toolbarControls hides:

sample-image.svgOverlay controls float over the image
sample-image.svg
Loading document
import { DocViewer } from 'mantine-doc-viewer';

function Demo() {
  return (
    <DocViewer
      src="/sample-image.svg"
      withOverlayControls
      toolbarControls={{ rotate: false, print: false, download: false }}
      toolbarProps={{ subtitle: 'Overlay controls float over the image' }}
      h={360}
    />
  );
}

The names that controls and toolbarControls take are title, thumbnails, pages, zoom, rotate, layout, outline, info, presentation, editPages, markup, search, print, download, fullscreen, wrap (text files) and viewMode (JSON and markdown).

Pages and thumbnails

The thumbnails button in the toolbar shows a thumbnail for every page. Thumbnails are drawn as they scroll into view, the current page is highlighted and choosing a thumbnail scrolls to its page. Set defaultThumbnailsOpened on the root to show them when the PDF opens, and defaultThumbnailsPosition to start on any of the four sides. At the top or bottom they form one row that scrolls sideways. Readers can move the thumbnails with the panel position button, and width of DocViewer.Thumbnails sets their size.

The page layout button offers single pages (the default), two pages side by side, two pages with the first page on its own as a cover, one row scrolled sideways, and rows that wrap. defaultPageLayout sets the layout when the PDF opens, gap of DocViewer.Pages the space between pages, and withScrollSnap stops scrolling at the start of each page or spread.

sample.pdf
Loading document
import { DocViewer } from 'mantine-doc-viewer';

function Demo() {
  return (
    <DocViewer
      src="/sample.pdf"
      defaultThumbnailsOpened
      defaultThumbnailsPosition="right"
      defaultPageLayout="two-page-cover"
      pagesProps={{ gap: 'xl', withScrollSnap: true }}
      thumbnailsProps={{ width: 96 }}
      h={500}
    />
  );
}

Only pages near the view are drawn, and pages further away give back their canvas, text layer and memory. Only the parts of the file needed for the pages on screen are downloaded, when the server supports range requests. A page canvas is kept under 16.7 million pixels, Safari's limit, and beyond that zoomed pages are drawn at a lower resolution instead of going blank. Change the limit with maxCanvasPixels of DocViewer.Pages.

Links in PDF pages are clickable. Links to another part of the document scroll the viewer to that spot without changing the page URL. Web links open in a new tab, and only http, https, mailto and tel links open at all. Screen readers read links within the document as "Go to page 3", and web links by their address. DocViewer.Pages has the events for what readers do on the pages:

PropCalled
onLinkClickWith the address when a web link is clicked, before it opens. event.preventDefault() stops it, for example to confirm before leaving
onTextSelectWith the text, the page it starts on and its boxes in page coordinates when the reader selects text. Not called when the selection is cleared
onReadingProgressWith { seen, position, reachedEnd } when how much of the PDF has been seen changes
onReachEndOnce, when the bottom of the last page is on screen

renderPageOverlay puts content of your app over each page, for example comment pins with their own status. It gets the page number, the page size at 100% and the scale of the page, and places content in page coordinates times scale, from the top left of the page. The overlay turns with the page when readers rotate it. The function runs again for every page when it changes and when the zoom changes, so keep it cheap, and wrap it in useCallback if it does not depend on the render of your component:

sample.pdf
Loading document
import { Badge } from '@mantine/core';
import { DocViewer, DocViewerPageOverlayInfo } from 'mantine-doc-viewer';

function renderPageOverlay({ page, scale }: DocViewerPageOverlayInfo) {
  return (
    <Badge
      color="red"
      style={{ position: 'absolute', top: 24 * scale, right: 24 * scale }}
    >
      Comment on page {page}
    </Badge>
  );
}

function Demo() {
  return (
    <DocViewer
      src="/sample.pdf"
      pagesProps={{ renderPageOverlay }}
      h={500}
    />
  );
}

Pages turn by themselves in an app that animates them, like a book: withScroll={false} stops reader scrolling while text selection, zoom and the store keep working, withPageTurning turns pages by spread with edge clicks, swipes and the arrow keys, and the goToPage action takes { behavior: 'instant' } to jump without a smooth scroll.

Search, outline and document info

DocViewer.Search is the search bar of a PDF, with match case, whole words and match accents buttons. Accents are ignored by default, so "cafe" also finds "café". Open search with the search button or with Ctrl or Cmd and F while the document has focus, move between matches with Enter and Shift and Enter, and close it with Escape. inputProps reach the search box, for example to change the placeholder.

PDFs with bookmarks get an outline button that lists them, and choosing one scrolls to its page. The info button lists the properties of the PDF (title, author, dates, PDF version, file size, page count and size), the files attached to it to download, and a checkbox to show or hide each layer (optional content). The presentation button shows one page at a time, fitted to the screen on a dark background and full screen where the browser allows it. Arrow keys, Space, Page Up and Page Down, Home and End move between pages, a click shows the next page, and Escape ends the presentation on the page it was on.

The store has the same actions as the buttons, so your app can drive search and mark passages. openSearch(query) opens the bar with a query typed in, and highlight marks the first place a text is found, or boxes on a page, in the colors of the active match and scrolls to it:

sample.pdf
Loading document
import { Button, Group, Stack } from '@mantine/core';
import { DocViewer, useDocViewer } from 'mantine-doc-viewer';

function Demo() {
  const [store, viewer] = useDocViewer();

  return (
    <Stack>
      <Group>
        <Button variant="default" onClick={() => viewer.openSearch('page 2')}>
          Search for "page 2"
        </Button>
        <Button variant="default" onClick={() => viewer.highlight({ text: 'Line 3', page: 3 })}>
          Highlight a line on page 3
        </Button>
        <Button variant="default" onClick={() => viewer.clearHighlight()}>
          Clear highlight
        </Button>
      </Group>

      <DocViewer.Root src="/sample.pdf" store={store} h={460}>
        <DocViewer.Toolbar>
          <DocViewer.OutlineButton />
          <DocViewer.InfoButton />
          <DocViewer.SearchButton />
        </DocViewer.Toolbar>
        <DocViewer.Search inputProps={{ placeholder: 'Find in document' }} />
        <DocViewer.Main />
      </DocViewer.Root>
    </Stack>
  );
}

Matches are highlighted with the CSS Custom Highlight API. matchColor and activeMatchColor of DocViewer.Pages set their colors, or style the highlights in your global styles:

::highlight(mantine-doc-viewer-match) {
  background-color: rgb(250 176 5 / 40%);
}

::highlight(mantine-doc-viewer-active-match) {
  background-color: rgb(253 126 20 / 65%);
}

Zoom and page layouts

A zoom is a scale where 1 is 100%, 'fit' (the default) to fit PDF pages to the width of the view and images to the whole view, or 'fit-page' to fit whole PDF pages, or spreads, to both the width and the height. Zoom with the toolbar, with the keys, with Ctrl or Cmd and the mouse wheel or with a trackpad pinch; zoom keeps the point under the pointer in place. The rotate button turns all PDF pages or the image a quarter turn. It only changes the view, the file is not changed.

Zoom and page layout are controlled like the value of a Mantine input: zoom with onZoomChange and pageLayout with onPageLayoutChange. Every zoom request goes to onZoomChange with the scale it gives, and shows once you pass it back. A fitted zoom reports a new scale when the view is resized. zoom and pageLayout have a default prop for the uncontrolled state, defaultZoom and defaultPageLayout.

page and fullscreen follow their prop rather than hold it. page scrolls the reader to that page when it changes, the reader can scroll away, and onPageChange reports where they are; defaultPage is the page a PDF opens on, and onPageChange is not called for it. fullscreen with onFullscreenChange enters and leaves full screen, and has no default prop:

Scale: 100%

sample.pdf
Loading document
import { SegmentedControl, Stack, Text } from '@mantine/core';
import { DocViewer, DocViewerPageLayout, DocViewerZoom } from 'mantine-doc-viewer';

function parseZoom(value: string): DocViewerZoom {
  return Number.isNaN(Number(value)) ? (value as DocViewerZoom) : Number(value);
}

function Demo() {
  const [zoom, setZoom] = useState<DocViewerZoom>('fit');
  const [scale, setScale] = useState(1);
  const [layout, setLayout] = useState<DocViewerPageLayout>('single');

  return (
    <Stack>
      <SegmentedControl
        value={String(zoom)}
        onChange={(value) => setZoom(parseZoom(value))}
        data={[
          { label: 'Fit width', value: 'fit' },
          { label: 'Fit page', value: 'fit-page' },
          { label: '100%', value: '1' },
          { label: '200%', value: '2' },
        ]}
      />
      <SegmentedControl
        value={layout}
        onChange={(value) => setLayout(value as DocViewerPageLayout)}
        data={['single', 'two-page', 'two-page-cover', 'horizontal', 'wrapped']}
      />
      <Text size="sm">Scale: {Math.round(scale * 100)}%</Text>

      <DocViewer
        src="/sample.pdf"
        zoom={zoom}
        onZoomChange={(value, details) => {
          setZoom(value);
          setScale(details.scale);
        }}
        pageLayout={layout}
        onPageLayoutChange={setLayout}
        h={440}
      />
    </Stack>
  );
}

Store API

Every viewer has a store, a Mantine store like createLightboxStore, that holds what the viewer shows and the actions on it. useDocViewer creates a store and actions bound to it for one viewer, and useDocViewerStore subscribes a component to the state. Pass the store to DocViewer or DocViewer.Root; without one, the viewer creates its own.

import { DocViewer, useDocViewer, useDocViewerStore } from 'mantine-doc-viewer';

function Demo() {
  const [store, viewer] = useDocViewer();
  const { page, numPages } = useDocViewerStore(store);

  return (
    <>
      <button onClick={() => viewer.goToPage(numPages)}>Last page ({page})</button>
      <DocViewer src="/report.pdf" store={store} />
    </>
  );
}

Actions do nothing for documents they do not apply to, and before the document is shown, so it is safe to call them at any time. Use them from handlers and effects:

loading

sample.pdf
Loading document
import { Button, Group, Stack, Text } from '@mantine/core';
import { DocViewer, useDocViewer, useDocViewerStore } from 'mantine-doc-viewer';

function Demo() {
  const [store, viewer] = useDocViewer();
  const { status, page, numPages } = useDocViewerStore(store);

  return (
    <Stack>
      <Group>
        <Button variant="default" onClick={() => viewer.previousSpread()}>
          Previous
        </Button>
        <Button variant="default" onClick={() => viewer.nextSpread()}>
          Next
        </Button>
        <Button variant="default" onClick={() => viewer.goToPage(numPages)}>
          Last page
        </Button>
        <Button variant="default" onClick={() => viewer.rotate()}>
          Rotate
        </Button>
        <Text size="sm">
          {status === 'ready' ? `Page ${page} of ${numPages}` : status}
        </Text>
      </Group>

      <DocViewer src="/sample.pdf" store={store} h={440} />
    </Stack>
  );
}

createDocViewer does the same outside of React, like createLightbox:

import { createDocViewer } from 'mantine-doc-viewer';

const [store, viewer] = createDocViewer();

viewer.goToPage(3);

The state has the type and status of the document, the page and spread in view, the zoom and its scale, the rotation, the page layout and what is open: type, status, info, error, numPages, page, spread, zoom, scale, rotation, pageLayout, thumbnailsOpened, thumbnailsPosition, searchOpened, presenting, fullscreen, canPrint, textWrap, viewMode, mode and markupTool. The actions are:

ActionDoes
goToPage(page, options)Scrolls a PDF to a page, or to a point of it with { top }
goToSpread(spread)Scrolls a PDF to a spread
nextSpread(options)Turns to the next spread, and with { loop: true } from the last to the first
previousSpread()Turns back to the previous spread
setZoom(zoom)zoomIn() and zoomOut() work like the toolbar buttons
setPageLayout(layout)Lays PDF pages out
rotate()Turns an image or PDF pages 90 degrees clockwise
openSearch(query)closeSearch() closes the bar
highlight(target)clearHighlight() removes it
toggleThumbnails(opened)setThumbnailsPosition(position) moves them to a side
togglePresentation()Starts or ends a presentation
toggleFullscreen()Shows the viewer full screen, or leaves full screen
print()download() downloads the document
getOutline()The outline of a PDF with page numbers
getBytes()The bytes of the document as shown
getPageCanvas(page)The canvas a PDF page is drawn on, to read from
resetReadingProgress()Forgets how much of the PDF has been seen, for the next reader
setTextWrap(wrap)Wraps long lines of text files, or shows them on one line
setViewMode(mode)Shows rendered markdown or a JSON tree with 'preview', or the file with 'source'

Events

DocViewer.Root and DocViewer call these when the document or the state of the viewer changes. Events for what happens inside PDF pages are on DocViewer.Pages, and the extensions have their own.

PropCalled
onDocumentLoadWith { type, numPages } for PDFs and { type, width, height } for images when the document is shown
onDocumentErrorWith the error when the document cannot be loaded
onPageChangeWith the PDF page that takes up most of the view
onZoomChangeWith the zoom and { scale }
onPageLayoutChangeWhen the reader picks a page layout
onFullscreenChangeWith what really happened when the viewer enters or leaves full screen, including Escape

Custom views

To show a file type that the viewer does not know, put your own view in DocViewer.Root. Use DocViewer.Toolbar, DocViewer.Body, DocViewer.Message and DocViewer.Loading to get the same toolbar, scroll area and messages as the built-in views, useDocViewerText to load a text file with the same size limit, and useDocViewerView to report the outcome. onLoad of the hook sets the status of the store to 'ready' and calls onDocumentLoad, and onError sets 'error' and calls onDocumentError. The built-in views do this themselves, a view you write has to call it.

useDocViewerContext gives the view the src, type, fileName and title of the document, the labels, the Styles API, the store and its actions. Custom toolbar buttons use it too: getControlProps(pressed) gives an ActionIcon the size, colors and control Styles API selector of the built-in buttons, and actions drives the viewer it is in, also when the viewer created its own store:

import { ActionIcon } from '@mantine/core';
import { useDocViewerContext } from 'mantine-doc-viewer';

function FirstPageButton() {
  const { actions, getControlProps } = useDocViewerContext();
  return (
    <ActionIcon {...getControlProps()} aria-label="First page" onClick={() => actions.goToPage(1)}>
      1
    </ActionIcon>
  );
}

The demo shows a CSV file as a table, with a toolbar button that adds totals:

sample.csv
Cannot show this file
import { useEffect, useState } from 'react';
import { ActionIcon, Table } from '@mantine/core';
import {
  DocViewer,
  useDocViewerContext,
  useDocViewerText,
  useDocViewerView,
} from 'mantine-doc-viewer';

function parseCsv(text: string) {
  return text
    .trim()
    .split('\n')
    .map((line) => line.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map((cell) => cell.replace(/"/g, '')));
}

function CsvView({ totals }: { totals: boolean }) {
  const { src } = useDocViewerContext();
  const { onLoad, onError } = useDocViewerView();
  const state = useDocViewerText(src, 1_000_000);

  useEffect(() => {
    if (state.status === 'ready') {
      onLoad({ byteSize: state.size });
    }
    if (state.status === 'error') {
      onError(state.error);
    }
  }, [state, onLoad, onError]);

  if (state.status !== 'ready') {
    return <DocViewer.Message error={state.status === 'error'}>Cannot show this file</DocViewer.Message>;
  }

  const [head, ...body] = parseCsv(state.text);
  const foot = head.map((_, column) => {
    const values = body.map((row) => Number(row[column]));
    return column === 0 ? 'Total' : values.some(Number.isNaN) ? '' : String(values.reduce((a, b) => a + b));
  });

  return (
    <DocViewer.Body>
      <Table data={{ head, body, foot: totals ? foot : undefined }} striped />
    </DocViewer.Body>
  );
}

function SummaryButton({ onClick, pressed }: { onClick: () => void; pressed: boolean }) {
  const { getControlProps } = useDocViewerContext();

  return (
    <ActionIcon {...getControlProps(pressed)} aria-label="Totals" aria-pressed={pressed} onClick={onClick}>
      Σ
    </ActionIcon>
  );
}

function Demo() {
  const [totals, setTotals] = useState(false);

  return (
    <DocViewer.Root src="/sample.csv" h={340}>
      <DocViewer.Toolbar>
        <SummaryButton pressed={totals} onClick={() => setTotals((value) => !value)} />
      </DocViewer.Toolbar>
      <CsvView totals={totals} />
    </DocViewer.Root>
  );
}

Page editor extension

Editing PDF pages is an extension, so apps that do not use it never download it. Create it with createPageEditorExtension from mantine-doc-viewer/editor, once, and pass it in extensions of the viewer. It adds an edit pages button to the toolbar, an editor where readers can reorder, turn, delete and extract pages, and drag and delete actions on the thumbnails of the sidebar.

import { DocViewer } from 'mantine-doc-viewer';
import { createPageEditorExtension } from 'mantine-doc-viewer/editor';

const pageEditor = createPageEditorExtension({
  onDocumentChange: async (bytes, { reason, pages }) => {
    await upload(new Blob([bytes], { type: 'application/pdf' }), { reason, pages });
  },
});

<DocViewer src="/contract.pdf" extensions={[pageEditor]} />;

In the editor readers can:

  • select pages with a click, Shift or Ctrl click, Space, or Ctrl or Cmd and A
  • reorder them by dragging (with a mouse, or with touch or a pen by the grip on each page), with the move earlier and move later buttons, or Alt and the arrow keys
  • delete them with the delete button or the Delete key (a PDF always keeps at least one page)
  • turn them a quarter turn with the rotate button or the R key; the turn is saved into the PDF
  • extract the selected pages as a new PDF

Done shows the edited document in the viewer; Save does the same and also calls onDocumentChange with the new PDF. The original file is never changed. Without onDocumentChange, saved PDFs are downloaded, and so are extracted pages without onExtract. Reordering or deleting thumbnails in the sidebar shows the changed document and calls onDocumentChange with reason: 'reorder' or 'delete'; without a callback nothing is downloaded. withThumbnailEditing={false} turns the sidebar editing off, and compact shows icon buttons with their labels in tooltips.

Turning pages writes their rotation with @cantoo/pdf-lib, which is loaded only when a page has been turned. The extension also exports DocViewerPageEditorButton and DocViewerPageEditor for custom toolbars and layouts, openPageEditor and closePageEditor to drive the editor from your own buttons, and DEFAULT_LABELS of the editor. Save a page in the demo:

Edit pages, then press Save

sample.pdf
Loading document
import { Stack, Text } from '@mantine/core';
import { DocViewer } from 'mantine-doc-viewer';
import { createPageEditorExtension } from 'mantine-doc-viewer/editor';

function Demo() {
  const [message, setMessage] = useState('Edit pages, then press Save');
  const [extensions] = useState(() => [
    createPageEditorExtension({
      onDocumentChange: (bytes, { reason, pages }) =>
        setMessage(`${reason}: ${bytes.byteLength} bytes, ${pages.length} pages`),
    }),
  ]);

  return (
    <Stack>
      <Text size="sm">{message}</Text>
      <DocViewer src="/sample.pdf" extensions={extensions} defaultThumbnailsOpened h={440} />
    </Stack>
  );
}

Markup extension

Markup is an extension too, from mantine-doc-viewer/markup. createMarkupExtension adds a markup button to the toolbar and a bar below it with tools to highlight, draw with a pen, type text boxes, draw rectangles, ellipses and revision clouds, and sign. Undo removes the last mark; Save writes the marks into the PDF as real annotations (pdf.js writes them, so other PDF readers show and edit them) and calls onDocumentChange with reason: 'annotate', or downloads the PDF.

tools picks the tools in the bar, and color, width and fontSize style new marks. Marks are data: value, defaultValue and onChange hold them, in PDF points from the top left of each page. The tool can be controlled too, with tool, defaultTool and onToolChange, so an app can use its own buttons instead of the bar with setMarkupTool(tool, store), and saveMarkup(store) saves. DocViewerMarkupBar and DocViewerMarkupButton are the parts for custom layouts.

The extension reads its options on every render, so controlled options work like the value of a Mantine input: call createMarkupExtension in the component, pass value and onChange, and the marks follow your state. Pages do not render again when only the options change.

Content that belongs to the app rather than the PDF, such as comment pins, goes in renderPageOverlay instead. Draw a mark in the demo, then clear the marks from outside the viewer:

0 marks. Pick a tool in the markup bar and draw on the page.

sample.pdf
Loading document
import { useState } from 'react';
import { Button, Group, Stack, Text } from '@mantine/core';
import { DocViewer } from 'mantine-doc-viewer';
import { createMarkupExtension, type DocViewerMark } from 'mantine-doc-viewer/markup';

function Demo() {
  const [marks, setMarks] = useState<DocViewerMark[]>([]);
  const markup = createMarkupExtension({
    tools: ['highlight', 'pen', 'text', 'cloud'],
    color: 'red',
    value: marks,
    onChange: setMarks,
  });

  return (
    <Stack>
      <Group>
        <Text size="sm">{marks.length} marks. Pick a tool in the markup bar and draw on the page.</Text>
        <Button size="xs" variant="default" disabled={marks.length === 0} onClick={() => setMarks([])}>
          Clear
        </Button>
      </Group>
      <DocViewer src="/sample.pdf" extensions={[markup]} h={440} />
    </Stack>
  );
}

Extensions are plain objects. Create them in render when they take controlled options, as in the demo, or once, outside of the component or with useState, when they do not; either way the viewer keeps its parts mounted. Passing both extensions at once works: extensions={[pageEditor, markup]}.

Kiosk recipe

A kiosk goes back to the start when nobody touches it, and plays the document to attract the next visitor. The viewer has no timer for this, because Mantine already has the parts: useIdle from @mantine/hooks says when nothing was touched, and useInterval turns pages with the nextSpread action. Pass { initialState: false } to useIdle: by default it starts as idle, and the loop would start when the page mounts.

Leave it alone for 8 seconds, or touch it to stop

sample.pdf
Loading document
import { Stack, Text } from '@mantine/core';
import { useIdle, useInterval } from '@mantine/hooks';
import { DocViewer, useDocViewer } from 'mantine-doc-viewer';

function Demo() {
  const [store, viewer] = useDocViewer();

  // initialState: false, the default (true) would start the loop as soon as the page mounts
  const idle = useIdle(8_000, { initialState: false });
  const attract = useInterval(() => viewer.nextSpread({ loop: true }), 3_000);

  useEffect(() => {
    if (idle) {
      viewer.goToPage(1);
      viewer.setZoom('fit-page');
      attract.start();
    } else {
      attract.stop();
    }
    return attract.stop;
  }, [idle]);

  return (
    <Stack>
      <Text size="sm">
        {idle ? 'Idle: turning pages by itself' : 'Leave it alone for 8 seconds, or touch it to stop'}
      </Text>
      <DocViewer src="/sample.pdf" store={store} h={400} />
    </Stack>
  );
}

For a real kiosk, set a longer timeout, hide print, download and fullscreen with toolbarControls, and use withPageTurning for pedals and touch.

Labels and locale

Every button name, message and screen reader text can be changed with labels. Labels that include a number are functions. Labels that are not set fall back to the English DEFAULT_LABELS, which also gives the type of every label, DocViewerLabels. locale is a BCP 47 language tag, such as 'de-DE', for the numbers and dates the viewer shows: zoom, page counts, file sizes and document properties. It is the browser's language by default.

The extensions have their own labels option, with DEFAULT_LABELS exported from mantine-doc-viewer/editor and mantine-doc-viewer/markup:

sample.pdf
Loading document
import { DocViewer } from 'mantine-doc-viewer';

function Demo() {
  return (
    <DocViewer
      src="/sample.pdf"
      locale="de-DE"
      labels={{
        previousPageLabel: 'Vorherige Seite',
        nextPageLabel: 'Nächste Seite',
        pageOfLabel: (page, total) => `Seite ${page} von ${total}`,
        zoomInLabel: 'Vergrößern',
        zoomOutLabel: 'Verkleinern',
        downloadLabel: 'Herunterladen',
        printLabel: 'Drucken',
      }}
      h={440}
    />
  );
}

To change labels for all viewers in your application, set labels in the default props of the DocViewer component with DocViewer.extend.

Styles API

DocViewer and its parts support Styles API, so you can style any inner element with classNames, styles, vars, attributes and unstyled, on DocViewer, DocViewer.Root or a part. The selectors are shared: a part styles the same elements whether it is in the default layout or in your own, so the Styles API tab has one table for all parts. The root takes size for the toolbar height, buttons and text, color for pressed buttons, the current thumbnail and focus outlines, radius, pageBackground for the color behind PDF pages and thumbnails, and pageColorScheme.

pageColorScheme="dark" inverts PDF pages for dark interfaces, keeping hues so images and charts stay recognisable, and pageColorScheme="auto" does so only when the Mantine color scheme is dark. variant="plain" removes the border, rounded corners, backgrounds and page shadows, for a document embedded in an article. Combine it with withToolbar={false} for just the pages.

sample.pdf
Loading document
import { DocViewer } from 'mantine-doc-viewer';

function Demo() {
  return (
    <DocViewer
      src="/sample.pdf"
      size="md"
      color="grape"
      radius="xl"
      pageColorScheme="auto"
      defaultThumbnailsOpened
      styles={{
        toolbar: { borderBottomWidth: 2 },
        thumbnail: { borderRadius: 'var(--mantine-radius-md)' },
      }}
      h={440}
    />
  );
}

autosize makes the viewer as tall as its content, so the page scrolls instead of a window inside the page. A PDF shows all its pages, and the page number, the goToPage action and search follow the scroll of the page. Text, code and markdown grow too; images keep a minimum height, so give them a fixed h. In full screen the viewer fills the screen and scrolls inside, as usual.

This is which selectors each part uses:

PartSelectors
DocViewer.Toolbartoolbar, toolbarSection, controls
DocViewer.Titleheading, title, subtitle
DocViewer.PageControlspageControls, pageIndicator, control
DocViewer.ZoomControlszoomControls, zoomLevel, dropdown, control
DocViewer.ThumbnailsButtoncontrol, dropdown
DocViewer.RotateButtoncontrol
DocViewer.LayoutMenucontrol, dropdown
DocViewer.OutlineButtoncontrol, dropdown, outline, outlineList, outlineItem
DocViewer.InfoButtoncontrol, dropdown, documentInfo, documentHeading, documentLayer, properties, outlineItem
DocViewer.PresentationButtoncontrol
DocViewer.SearchButtoncontrol
DocViewer.PrintButtoncontrol
DocViewer.DownloadButtoncontrol
DocViewer.FullscreenButtoncontrol
DocViewer.WrapButtoncontrol
DocViewer.ViewModeControlviewMode
DocViewer.Mainmain
DocViewer.Bodybody
DocViewer.Pagesbody, pages, page, canvas, textLayer, linkLayer, pageOverlay, highlightLayer, highlight, empty, password, passwordInput, passwordSubmit
DocViewer.Thumbnailsthumbnails, thumbnail, thumbnailImage, thumbnailLabel, thumbnailDelete, dragHandle, canvas
DocViewer.Searchsearch, searchInput, searchCount, searchOption, control
DocViewer.Outlineoutline, outlineList, outlineItem
DocViewer.DocumentInfodocumentInfo, documentHeading, documentLayer, properties, outlineItem
DocViewer.PresentationControlspresentationControls, pageIndicator, control
DocViewer.OverlayControlsoverlayControls, overlayControl
DocViewer.Imagebody, image, imageStage, imageCanvas, imageFrame, imageOverlay
DocViewer.Textbody, text, empty
DocViewer.Codebody, code, empty
DocViewer.Markdownbody, markdown, code, empty
DocViewer.Messageempty
DocViewer.Loadingempty
DocViewerPageEditoreditor, editorBar, editorTitle, editorCount, editorPages, editorPage, editorButton, thumbnailImage, thumbnailLabel, dragHandle, canvas
DocViewerPageEditorButtoncontrol
DocViewerMarkupBarmarkupBar, markupDivider, markupSave, control
DocViewerMarkupButtoncontrol

Keyboard shortcuts

The scroll area of each document can be focused with Tab and lists its shortcuts in aria-keyshortcuts. Shortcuts work while the document has focus.

WhereKeyAction
Images and PDF pages+Zoom in (= works too)
Images and PDF pages-Zoom out
Images and PDF pages0Fit to view
ImagesrRotate 90 degrees clockwise
PDF pagesCtrl or Cmd + FOpen search
SearchEnterNext match (Shift and Enter for the previous one)
SearchEscapeClose search
ThumbnailsArrow keys, Page Up, Page Down, Home, EndShow another page
Pages with withPageTurningArrow left and right, Page Up, Page DownTurn the page
PresentationArrow keys, Space, Page Up, Page Down, Home, EndMove between pages
PresentationEscapeEnd the presentation on the current page
Page editorSpace, Ctrl or Cmd + A, R, Delete, Alt + arrow keysSelect, select all, rotate, delete, move pages

Accessibility

  • Screen readers read PDF pages from their text layer. Each page is a group named "Page 2 of 3".
  • The scroll area of each document is a region named after fileName, with the keyboard shortcuts in aria-keyshortcuts.
  • Set alt of DocViewer.Image (imageProps={{ alt }}) to describe images. Without it, the file name is used.
  • The page buttons and thumbnails announce the new page, and search announces the match count and the active match with its page once results settle. Load errors are announced as alerts.
  • Links in markdown that open a new tab say so to screen readers.
  • Thumbnails are a listbox with one tab stop on the current page. Arrow keys, Page Up, Page Down, Home and End move to another thumbnail and show its page; screen readers read "Page 3, 3 of 50, selected".
  • Buttons that become unavailable, such as Next page on the last page, keep focus.
  • In Windows high contrast mode, pressed toggle buttons get an outline.
  • Everything the viewer says is in labels, so translating it translates the screen reader text too.