PDF pages rendered with pdf.js, with selectable text, find, links, zoom and page navigation
Tags: viewer pdf document pdfjs
PdfViewer renders PDF pages with pdf.js (opens in new tab). Pages draw on canvas with a text layer on top, so text can be selected, copied, found and read by screen readers. Links work: links inside the document jump to their page, and web links open in a new tab.
Usually shown through DocumentViewer. Use
PdfViewerdirectly when you already know the file is a PDF.
Import
<script>
import { PdfViewer } from '@classic-homes/viewer-svelte/pdf';
</script>Setup
npm install @classic-homes/viewer-svelte pdfjs-distpdf.js parses in a worker. Point it at the worker file once, at app start:
import { configurePdf } from '@classic-homes/viewer-svelte/pdf';
import workerSrc from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
configurePdf({ workerSrc });configurePdf also takes cMapUrl, standardFontDataUrl and wasmUrl (base URLs of the matching pdfjs-dist folders, with a trailing slash). Without them, PDFs that rely on non-embedded CJK fonts, the 14 standard fonts or JPEG 2000 images may show substitute fonts or missing images. Most PDFs embed their fonts.
Basic Usage
<script lang="ts">
import { loadSource } from '@classic-homes/viewer-svelte';
import { PdfViewer } from '@classic-homes/viewer-svelte/pdf';
</script>
{#await loadSource('/plans/lot-12.pdf') then source}
<PdfViewer {source} kind="pdf" initialZoom="fit-page" class="h-[80vh]" />
{/await}Props
| Prop | Type | Default | Description |
|---|---|---|---|
source |
LoadedSource |
required | Loaded bytes plus name and MIME hints (loadSource) |
kind |
RenderableKind |
required | 'pdf' |
initialZoom |
ZoomMode |
'fit-width' |
'fit-width', 'fit-page' or a scale such as 1.5 |
initialPage |
number |
1 |
1-based page to open at |
hideToolbar |
boolean |
false |
Hide the toolbar |
onready |
() => void |
- | The first page is on screen |
onerror |
(error: ViewerError) => void |
- | Parsing or rendering failed |
class |
string |
- | Classes for the outer element |
Features
- Toolbar: page number field, previous/next, zoom in/out, fit, find, print, download and fullscreen.
- Pages are virtualised: only visible pages (plus one either side) render, at the screen's pixel density, so long documents stay fast.
- Ctrl/Cmd + wheel and pinch zoom keep the point under the pointer still.
- Password-protected PDFs get an "encrypted" state with a download button. PDFs with only an owner password (printing or copying restrictions) open normally.
Accessibility
- The viewer is a labelled region; every control is reachable with Tab and has an accessible name.
- The text layer is real text, so screen readers read the page and find highlights matches.
- Shortcuts: Ctrl/Cmd +
+/-/0zoom, Ctrl/Cmd + F find, PageUp/PageDown and Home/End move between pages.
Related
- DocumentViewer: detects the format and loads the right viewer
- DocxViewer: Word documents as pages