Skip to content

Commit 56dd218

Browse files
authored
feat: load pdf document from src with shared worker (#13259)
1 parent dd7c272 commit 56dd218

22 files changed

Lines changed: 1242 additions & 10 deletions

‎dev/pdf-viewer.html‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,49 @@
1212
</script>
1313
<script type="module">
1414
import '@vaadin/pdf-viewer';
15+
16+
const viewer = document.querySelector('vaadin-pdf-viewer');
17+
const select = document.querySelector('#src');
18+
const log = document.querySelector('#log');
19+
20+
const update = () => {
21+
viewer.src = select.value;
22+
};
23+
select.addEventListener('change', update);
24+
25+
viewer.addEventListener('document-load', (e) => {
26+
log.textContent = `document-load: ${JSON.stringify(e.detail)}`;
27+
});
28+
viewer.addEventListener('document-error', (e) => {
29+
log.textContent = `document-error: ${e.detail.reason}`;
30+
});
31+
32+
update();
1533
</script>
34+
<style>
35+
vaadin-pdf-viewer {
36+
height: 600px;
37+
}
38+
</style>
1639
</head>
1740

1841
<body>
42+
<p>
43+
<label>
44+
Document
45+
<select id="src">
46+
<option value="/dev/assets/pdf/01_fonts.pdf">01_fonts.pdf</option>
47+
<option value="/dev/assets/pdf/02_images_and_vector_graphics.pdf">02_images_and_vector_graphics.pdf</option>
48+
<option value="/dev/assets/pdf/03_form_with_signatures.pdf">03_form_with_signatures.pdf</option>
49+
<option value="/dev/assets/pdf/04_optional_content_help_layer.pdf">04_optional_content_help_layer.pdf</option>
50+
<option value="/dev/assets/pdf/05_tagged_accessible_pdf_ua.pdf">05_tagged_accessible_pdf_ua.pdf</option>
51+
<option value="/packages/pdf-viewer/test/fixtures/encrypted.pdf">Password-protected file</option>
52+
<option value="/packages/pdf-viewer/test/fixtures/invalid.pdf">Invalid file</option>
53+
<option value="/does-not-exist.pdf">Missing file</option>
54+
</select>
55+
</label>
56+
<output id="log"></output>
57+
</p>
1958
<vaadin-pdf-viewer></vaadin-pdf-viewer>
2059
</body>
2160
</html>
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# PDF Viewer Architecture
2+
3+
This file describes the internals of `<vaadin-pdf-viewer>`.
4+
5+
The [fixtures README](test/fixtures/README.md) describes the PDF files that the unit tests use and
6+
how to generate them.
7+
8+
## Worker and bundlers
9+
10+
- The component loads [pdf.js](https://mozilla.github.io/pdf.js/) (legacy build) when the first
11+
`src` is set. Importing the component therefore costs little.
12+
- pdf.js runs in a module worker. The component creates it from a file of this package with
13+
`new Worker(new URL('./pdf-viewer-worker.js', import.meta.url), { type: 'module' })`.
14+
- Vite supports this pattern in the dev server and in production builds without configuration.
15+
Other bundlers must support module workers created with `new URL(..., import.meta.url)`.
16+
- All viewers on a page share one worker. The worker stops when no viewer has a document.
17+
- The viewer does not change the global worker options of pdf.js (`GlobalWorkerOptions`). Other
18+
pdf.js users on the page keep their own settings.
19+
- The viewer has no fallback to the main thread. When the worker cannot load, the viewer fires
20+
`document-error` with the reason `network` and logs a warning about `worker-src`.
21+
22+
## Requests
23+
24+
- The viewer requests a document with one GET request. It does not use range requests, even
25+
when the server supports them.
26+
- The first document also loads the pdf.js library and its worker script.
27+
28+
## Install size
29+
30+
- The package depends on `pdfjs-dist`, which takes about 35 MB unpacked. Only the parts that the
31+
viewer imports go into the browser bundle.
32+
- `pdfjs-dist` has an optional dependency, `@napi-rs/canvas`, with native binaries of about
33+
30 MB. pdf.js uses it only in Node.js, and it is not part of the browser bundle. To skip it,
34+
install with `npm i --omit=optional`.
35+
- `pdfjs-dist` declares Node.js 22.13 or newer.
36+
37+
## Browser support
38+
39+
- The viewer requires Safari and iOS Safari 18 or newer while it is experimental. This is one
40+
version above the general Vaadin minimum, Safari 17.6.
41+
- The viewer uses the legacy build of pdf.js, which supports more browser versions than the
42+
modern build. Safari 17.6 support is not checked yet.
43+
- Other browsers are supported as for all Vaadin components: latest Chrome, Edge and Firefox.

‎packages/pdf-viewer/package.json‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,11 @@
3434
"web-component"
3535
],
3636
"dependencies": {
37+
"@open-wc/dedupe-mixin": "^1.3.0",
3738
"@vaadin/component-base": "25.4.0-alpha4",
3839
"@vaadin/vaadin-themable-mixin": "25.4.0-alpha4",
39-
"lit": "^3.0.0"
40+
"lit": "^3.0.0",
41+
"pdfjs-dist": "6.4.299"
4042
},
4143
"devDependencies": {
4244
"@vaadin/aura": "25.4.0-alpha4",
Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
/**
2+
* @license
3+
* Copyright (c) 2000 - 2026 Vaadin Ltd.
4+
*
5+
* This program is available under Vaadin Commercial License and Service Terms.
6+
*
7+
*
8+
* See https://vaadin.com/commercial-license-and-service-terms for the full
9+
* license.
10+
*/
11+
import { issueWarning } from '@vaadin/component-base/src/warnings.js';
12+
import { acquireWorker, loadPdfjs, releaseWorker } from './pdfjs-loader.js';
13+
14+
/**
15+
* Maps a pdf.js loading error to the `reason` reported in the `document-error`
16+
* event. Any failure other than a password or an invalid file is reported as
17+
* `network`, since the file could not be fetched or read.
18+
* @param {Error} error
19+
* @return {'invalid' | 'network' | 'password'}
20+
*/
21+
function getErrorReason(error) {
22+
if (error && error.name === 'PasswordException') {
23+
return 'password';
24+
}
25+
if (error && error.name === 'InvalidPDFException') {
26+
return 'invalid';
27+
}
28+
return 'network';
29+
}
30+
31+
/**
32+
* @typedef {Object} PdfViewerDocumentCallbacks
33+
* @property {() => void} onLoadStart Called when loading starts.
34+
* @property {(pdfDocument: import('pdfjs-dist').PDFDocumentProxy, title: string) => void} onLoad
35+
* Called when the document has loaded, with the title from its metadata.
36+
* @property {(error: unknown, reason: 'invalid' | 'network' | 'password') => void} onError
37+
* Called when the document could not be loaded.
38+
* @property {() => void} onUnload Called when the document or the load in progress is dropped.
39+
*/
40+
41+
/**
42+
* A controller that loads the document of the host's `src` with pdf.js, and
43+
* releases it while the host is detached.
44+
*/
45+
export class PdfViewerDocumentController {
46+
/** @type {HTMLElement & { src: string | null | undefined }} */
47+
#host;
48+
49+
/** @type {PdfViewerDocumentCallbacks} */
50+
#callbacks;
51+
52+
/** @type {import('pdfjs-dist').PDFDocumentLoadingTask | null} */
53+
#loadingTask = null;
54+
55+
/** @type {ReturnType<typeof acquireWorker> | null} */
56+
#workerHandle = null;
57+
58+
/** Incremented on every load, to detect results that belong to an outdated load. */
59+
#loadId = 0;
60+
61+
/** Set when the document is not loaded because the host is detached, to load it on attach. */
62+
#released = false;
63+
64+
/**
65+
* @param {HTMLElement & { src: string | null | undefined }} host
66+
* @param {PdfViewerDocumentCallbacks} callbacks
67+
*/
68+
constructor(host, callbacks) {
69+
this.#host = host;
70+
this.#callbacks = callbacks;
71+
}
72+
73+
hostConnected() {
74+
if (this.#released) {
75+
this.#released = false;
76+
this.load();
77+
}
78+
}
79+
80+
hostDisconnected() {
81+
// Wait a microtask so that moving the host in the DOM does not reload the document.
82+
queueMicrotask(() => {
83+
if (!this.#host.isConnected && this.#host.src && !this.#released) {
84+
this.#loadId += 1;
85+
this.#unload();
86+
this.#released = true;
87+
}
88+
});
89+
}
90+
91+
/**
92+
* Drops the current document and loads the one of the host's `src`.
93+
* A detached host does not hold on to a document. It loads it once attached.
94+
*/
95+
load() {
96+
this.#loadId += 1;
97+
const loadId = this.#loadId;
98+
this.#unload();
99+
100+
const { src } = this.#host;
101+
this.#released = !!src && !this.#host.isConnected;
102+
if (!src || this.#released) {
103+
return;
104+
}
105+
106+
this.#callbacks.onLoadStart();
107+
this.#open(loadId, src).catch((error) => {
108+
if (loadId === this.#loadId) {
109+
this.#unload();
110+
this.#callbacks.onError(error, getErrorReason(error));
111+
}
112+
});
113+
}
114+
115+
/** @private */
116+
async #open(loadId, src) {
117+
const pdfjs = await loadPdfjs();
118+
if (loadId !== this.#loadId) {
119+
return;
120+
}
121+
122+
this.#workerHandle = acquireWorker(pdfjs);
123+
this.#loadingTask = pdfjs.getDocument({
124+
url: new URL(src, document.baseURI).href,
125+
worker: this.#workerHandle.worker,
126+
// One request for the whole file, so that the server sends the document once.
127+
disableRange: true,
128+
// Security: no XFA forms. Scripting (pdf.sandbox) is never loaded either.
129+
enableXfa: false,
130+
});
131+
132+
const workerFailed = this.#workerHandle.failed.catch((error) => {
133+
issueWarning(
134+
'The pdf.js worker of <vaadin-pdf-viewer> failed to load. If the page has a Content Security Policy, check that its worker-src directive allows the worker script.',
135+
);
136+
throw error;
137+
});
138+
const pdfDocument = await Promise.race([this.#loadingTask.promise, workerFailed]);
139+
if (loadId !== this.#loadId) {
140+
return;
141+
}
142+
143+
const { info } = await pdfDocument.getMetadata();
144+
if (loadId !== this.#loadId) {
145+
return;
146+
}
147+
this.#callbacks.onLoad(pdfDocument, (info && info.Title) || '');
148+
}
149+
150+
/** @private */
151+
#unload() {
152+
const loadingTask = this.#loadingTask;
153+
const workerHandle = this.#workerHandle;
154+
this.#loadingTask = null;
155+
this.#workerHandle = null;
156+
if (loadingTask) {
157+
// Destroying the loading task also destroys its document. Release
158+
// the worker only afterwards, as destroying talks to the worker.
159+
loadingTask
160+
.destroy()
161+
.finally(() => releaseWorker(workerHandle))
162+
.catch((error) => issueWarning(`Failed to release the PDF document: ${error.message}`));
163+
} else if (workerHandle) {
164+
releaseWorker(workerHandle);
165+
}
166+
this.#callbacks.onUnload();
167+
}
168+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
/**
2+
* @license
3+
* Copyright (c) 2000 - 2026 Vaadin Ltd.
4+
*
5+
* This program is available under Vaadin Commercial License and Service Terms.
6+
*
7+
*
8+
* See https://vaadin.com/commercial-license-and-service-terms for the full
9+
* license.
10+
*/
11+
// Entry point of the pdf.js worker. Loaded as a module worker by the viewer, see `pdfjs-loader.js`.
12+
// The import has side effects only: pdf.js sets up its message handler when it runs inside a worker.
13+
import 'pdfjs-dist/legacy/build/pdf.worker.mjs';
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @license
3+
* Copyright (c) 2000 - 2026 Vaadin Ltd.
4+
*
5+
* This program is available under Vaadin Commercial License and Service Terms.
6+
*
7+
*
8+
* See https://vaadin.com/commercial-license-and-service-terms for the full
9+
* license.
10+
*/
11+
import type * as pdfjsLib from 'pdfjs-dist';
12+
import type { PDFWorker } from 'pdfjs-dist';
13+
14+
type Pdfjs = typeof pdfjsLib;
15+
16+
/**
17+
* The worker shared by all viewers on the page, with the number of documents
18+
* that use it.
19+
*/
20+
export interface WorkerHandle {
21+
worker: PDFWorker | null;
22+
port: Worker;
23+
failed: Promise<never> | null;
24+
users: number;
25+
pdfjs: Pdfjs;
26+
}
27+
28+
/**
29+
* Loads the pdf.js library on first use. The library is large, so it is not
30+
* loaded until a viewer actually needs to show a document.
31+
*/
32+
export function loadPdfjs(): Promise<Pdfjs>;
33+
34+
/**
35+
* Returns the pdf.js worker shared by all viewers on the page, creating it
36+
* when needed. Every call must be balanced by a call to `releaseWorker()`
37+
* with the returned handle.
38+
*
39+
* The worker is passed to each document explicitly, so that pdf.js'
40+
* `GlobalWorkerOptions` stay untouched for any other pdf.js user on the page.
41+
*/
42+
export function acquireWorker(pdfjs: Pdfjs): WorkerHandle;
43+
44+
/**
45+
* Releases a worker handle obtained with `acquireWorker()`, and terminates
46+
* the worker when no document uses it anymore.
47+
*/
48+
export function releaseWorker(handle: WorkerHandle): void;

0 commit comments

Comments
 (0)