mantine-doc-viewer
Document viewer for Mantine: PDF, images, text, code and markdown
Installation
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-distto show PDF filesreact-markdownandremark-gfmto render markdown files@cantoo/pdf-libformantine-doc-viewer/editor, which writes page rotations into a PDF; the markup extension does not need it
After installation import package styles at the root of your application:
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:
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:
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:
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:
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.
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:
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,languageofDocViewer.Codeoverrides 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:
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.
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:
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.
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:
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.
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:
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:
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:
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:
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%
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.
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
createDocViewer does the same outside of React, like createLightbox:
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:
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.
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:
The demo shows a CSV file as a table, with a toolbar button that adds totals:
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.
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
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.
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
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:
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.
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:
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.
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 inaria-keyshortcuts. - Set
altofDocViewer.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.