@imggion/html2realpdf 0.1.0 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,292 +1,238 @@
1
- # @imggion/html2realpdf
2
-
3
- Browser-first HTML-to-PDF rendering powered by Zig and WebAssembly. Text,
4
- vectors, links, and images are emitted as native PDF objects instead of a
5
- full-page screenshot.
1
+ <div align="center">
2
+ <img src="https://raw.githubusercontent.com/imggion/html2realpdf/main/docs/assets/html2realpdf-logo.webp" alt="html2realpdf logo" width="180">
3
+ <h1>html2realpdf</h1>
4
+ <p><strong>A real PDF, not a screenshot.</strong></p>
5
+ <p>
6
+ <a href="https://www.npmjs.com/package/@imggion/html2realpdf">
7
+ <img src="https://img.shields.io/npm/v/@imggion/html2realpdf.svg?style=flat-square" alt="npm version">
8
+ </a>
9
+ <a href="https://github.com/imggion/html2realpdf/releases/tag/v0.1.13">
10
+ <img src="https://img.shields.io/badge/release-0.1.13-2ea44f?style=flat-square" alt="Latest release: 0.1.13">
11
+ </a>
12
+ <img src="https://img.shields.io/badge/-zig-f39b34?style=flat-square&amp;logo=zig&amp;logoColor=white" alt="Zig">
13
+ <img src="https://img.shields.io/badge/-WASM-654ff0?style=flat-square&amp;logo=webassembly&amp;logoColor=white" alt="WebAssembly">
14
+ <img src="https://img.shields.io/badge/-TypeScript-3178c6?style=flat-square&amp;logo=typescript&amp;logoColor=white" alt="TypeScript">
15
+ </p>
16
+ <p>
17
+ Generate selectable, searchable, vector-based PDFs from HTML in the browser.<br>
18
+ Written in Zig, compiled to WebAssembly, and packaged with a typed TypeScript API.
19
+ </p>
20
+ </div>
21
+
22
+ ## Contents
23
+
24
+ - [Why real PDFs](#why-real-pdfs)
25
+ - [Install](#install)
26
+ - [Quick start](#quick-start)
27
+ - [React](#react)
28
+ - [Vue](#vue)
29
+ - [Preview](#preview)
30
+ - [Page layouts](#page-layouts)
31
+ - [Benchmark](#benchmark)
32
+ - [Contributing](#contributing)
33
+ - [License](#license)
34
+
35
+ ## Why real PDFs
36
+
37
+ Screenshot-based PDF tools turn a page into an image. `html2realpdf` keeps text
38
+ as text, links as PDF annotations, fonts as embedded subsets, and supported
39
+ graphics as vectors.
40
+
41
+ The text includes Unicode mappings, so people can select, copy, and search the
42
+ result. Tools and LLMs can read the document text without first running OCR.
43
+ Text-heavy documents are also often smaller and stay sharp at every zoom level.
44
+
45
+ Zig performs the layout and PDF writing, while WebAssembly brings the renderer
46
+ to the browser. The result is one portable pipeline for invoices, reports,
47
+ tickets, letters, slides, and other web-generated documents.
48
+
49
+ See the [CSS support matrix](docs/css-support.md) for the current layout and
50
+ rendering coverage. The current release provides machine-readable text and accessible
51
+ preview controls; it does not claim PDF/UA or fully tagged PDF compliance.
6
52
 
7
53
  ## Install
8
54
 
55
+ Install the stable release with your package manager:
56
+
9
57
  ```sh
10
58
  npm install @imggion/html2realpdf
59
+ pnpm add @imggion/html2realpdf
60
+ yarn add @imggion/html2realpdf
61
+ bun add @imggion/html2realpdf
11
62
  ```
12
63
 
13
- The package is ESM and includes TypeScript declarations, its Worker, WASM, and
14
- PDF.js preview assets. Imports are SSR-safe; rendering requires browser DOM APIs.
15
- Import values and types only from `@imggion/html2realpdf`.
64
+ ## Quick start
16
65
 
17
- ## Choose an API
66
+ Render an HTML element, download the PDF, then release its resources:
18
67
 
19
- | Need | API | Lifetime |
20
- | --- | --- | --- |
21
- | Default rendering with minimal setup | `renderPdf` | Cached package Worker for the application lifetime |
22
- | Repeated renders, custom fonts, or explicit cleanup | `createRenderer` | Caller-owned renderer |
23
- | Migration from supported html2pdf.js chains | Default `html2pdf` export | Compatibility worker with a cached PDF |
68
+ ```ts
69
+ import { renderPdf } from "@imggion/html2realpdf";
24
70
 
25
- Use the modern API for new integrations. The compatibility API deliberately
26
- rejects stages that depend on html2canvas or rasterized PDF pages.
71
+ const invoice = document.querySelector<HTMLElement>("#invoice");
72
+ if (!invoice) throw new Error("Invoice not found");
27
73
 
28
- ## Sources
74
+ const pdf = await renderPdf(invoice);
75
+ pdf.download("invoice.pdf");
76
+ pdf.dispose();
77
+ ```
29
78
 
30
- `renderPdf` and `renderer.render` accept:
79
+ HTML strings are supported too:
31
80
 
32
81
  ```ts
33
- type HtmlSource = string | Element | { readonly current: Element | null };
82
+ const pdf = await renderPdf("<h1>Hello from a real PDF</h1>");
34
83
  ```
35
84
 
36
- - A mounted `Element` preserves computed styles, pseudo-elements, live form
37
- state, canvas pixels, and other browser state.
38
- - A ref-shaped object supports React refs without adding React as a dependency.
39
- - An HTML string runs in an inert, CSP-restricted document. Scripts, event
40
- handlers, refresh directives, and active elements are removed.
85
+ ## React
41
86
 
42
- Prefer a mounted source when output must match live UI state. Render refs only
43
- after they are mounted; a null ref produces `InvalidSourceError`.
87
+ Pass a ref to a mounted element. The package understands React-shaped refs
88
+ without depending on React itself.
44
89
 
45
- ## Render once
90
+ ```tsx
91
+ const reportRef = useRef<HTMLDivElement>(null);
46
92
 
47
- ```ts
48
- import { renderPdf, type RenderOptions } from "@imggion/html2realpdf";
49
-
50
- const options: RenderOptions = {
51
- page: { format: "a4", unit: "mm", margin: [15, 12] },
52
- cssProfile: "web",
53
- mediaType: "print",
54
- fallback: "error",
55
- metadata: { title: "Invoice 2026-001" },
56
- };
57
-
58
- const pdf = await renderPdf(document.querySelector("#invoice")!, options);
59
- try {
60
- pdf.download("invoice.pdf");
61
- } finally {
93
+ async function downloadReport() {
94
+ if (!reportRef.current) return;
95
+
96
+ const pdf = await renderPdf(reportRef);
97
+ pdf.download("report.pdf");
62
98
  pdf.dispose();
63
99
  }
100
+
101
+ return <Report ref={reportRef} />;
64
102
  ```
65
103
 
66
- `renderPdf` lazily creates and caches a default Worker renderer. Use an explicit
67
- renderer when the backend must be disposed, configured with fonts, or forced to
68
- the main thread.
104
+ `Report` can be a component that forwards its ref to its root element. Pass the
105
+ mounted ref, not an unmounted component definition.
69
106
 
70
- ## Reuse a renderer
107
+ ## Vue
71
108
 
72
- ```ts
73
- import { createRenderer } from "@imggion/html2realpdf";
74
-
75
- const renderer = await createRenderer({
76
- execution: "worker",
77
- fonts: [{
78
- family: "Inter",
79
- data: await (await fetch("/fonts/Inter-Regular.ttf")).arrayBuffer(),
80
- weight: 400,
81
- style: "normal",
82
- }],
83
- });
109
+ Pass the mounted DOM element behind a template ref. With Vue 3.5 or newer,
110
+ `useTemplateRef()` keeps the element typed without wrapping the renderer in a
111
+ Vue-specific adapter.
84
112
 
85
- try {
86
- const pdf = await renderer.render(
87
- '<p style="font-family: Inter">Selectable text</p>',
88
- );
113
+ ```vue
114
+ <script setup lang="ts">
115
+ import { useTemplateRef } from "vue";
116
+ import { renderPdf } from "@imggion/html2realpdf";
117
+
118
+ const report = useTemplateRef<HTMLElement>("report");
119
+
120
+ async function downloadReport() {
121
+ if (!report.value) return;
122
+
123
+ const pdf = await renderPdf(report.value);
89
124
  try {
90
- const blob = pdf.toBlob();
91
- // Store or upload the Blob.
125
+ pdf.download("report.pdf");
92
126
  } finally {
93
127
  pdf.dispose();
94
128
  }
95
- } finally {
96
- renderer.dispose();
97
129
  }
98
- ```
130
+ </script>
99
131
 
100
- Worker execution is the default because synchronous WASM work would otherwise
101
- occupy the UI thread. Use `execution: "main"` only when Workers are unavailable
102
- or a controlled environment requires it. Override `wasmUrl` only when a deploy
103
- cannot serve package-relative assets. The published default asset is built with
104
- `ReleaseFast`. Repository consumers that prioritize transfer size can build the
105
- same ABI with `npm run build:small` and serve that asset through `wasmUrl`.
106
-
107
- ## Render options
108
-
109
- ### Page and CSS
110
-
111
- | Option | Default | Contract |
112
- | --- | --- | --- |
113
- | `page` | Captured `@page`, then A4 portrait with zero margins | Explicit API geometry wins over captured page geometry. Custom dimensions and margins use `page.unit`. |
114
- | `cssProfile` | `"document"` | `document` favors paged reports; `web` adds broader browser layout; `strict` uses web layout and rejects unsupported CSS by default. |
115
- | `unsupportedCss` | `"error"` in strict mode, otherwise `"warn"` | `warn` records diagnostics, `error` rejects, and `ignore` omits silently. |
116
- | `strict` | `false` | Promotes unsupported snapshot CSS to errors but does not select the `web` layout profile. Explicit `unsupportedCss` wins. |
117
- | `mediaType` | `"screen"` | Selects the media environment used during style resolution. |
118
- | `layoutContext` | `"source"` | `"page"` lets an implicit root width and authored auto inline margins resolve against the PDF content box. |
119
- | `viewport` | Source environment | Makes responsive layout and media queries deterministic. |
120
-
121
- Named page formats retain their physical dimensions regardless of `unit`.
122
- Custom `[width, height]` formats use that unit. Four-value margins follow
123
- html2pdf.js order `[top, left, bottom, right]`, not CSS shorthand order.
124
-
125
- ### Resources and browser state
126
-
127
- | Option | Default | Contract |
128
- | --- | --- | --- |
129
- | `baseUrl` | Source document URL | Resolves relative stylesheets and images. |
130
- | `resourcePolicy` | `"error"` | `omit` removes failed resources and records `RESOURCE_OMITTED`. |
131
- | `resourceResolver` | None | Resolves protected or virtual images and stylesheets. Fonts are renderer registrations. |
132
- | `includeShadowDom` | `false` | Flattens open Shadow DOM only. Closed roots are inaccessible. |
133
- | `enableLinks` | `true` | Set to `false` to remove link targets before rendering. |
134
-
135
- The resolver receives `{ kind: "image" | "stylesheet", url }`. For a
136
- stylesheet, a returned string is CSS source. For an image, a string is a
137
- supported data URL or replacement URL. Returning `null` applies
138
- `resourcePolicy`.
139
-
140
- External stylesheets in HTML-string input are inert and must be supplied by the
141
- resolver. Mounted DOM input can use stylesheets already accessible through the
142
- browser CSSOM.
143
-
144
- ### SVG and canvas
145
-
146
- | Option | Default | Contract |
147
- | --- | --- | --- |
148
- | `fallback` | `"error"` | Unsupported SVG fails unless `"rasterize-subtree"` explicitly permits scoped rasterization. |
149
- | `canvasToSvg` | None | Converts live canvases through a chart library's SVG exporter. Without it, canvases become transparent PNG images. |
150
- | `canvasFallback` | `"error"` | `"rasterize"` applies only when the adapter returns `null`. |
132
+ <template>
133
+ <article ref="report">
134
+ <h1>Quarterly report</h1>
135
+ <p>This content stays selectable in the PDF.</p>
136
+ </article>
151
137
 
152
- ```ts
153
- const pdf = await renderer.render(dashboardElement, {
154
- canvasToSvg: ({ canvas, cssWidth, cssHeight }) =>
155
- chartFor(canvas).toSvg({ width: cssWidth, height: cssHeight }),
156
- canvasFallback: "error",
157
- fallback: "error",
158
- });
138
+ <button type="button" @click="downloadReport">Download PDF</button>
139
+ </template>
159
140
  ```
160
141
 
161
- The adapter may return a complete SVG string, an `image/svg+xml` Blob, an
162
- `SVGSVGElement`, or a promise. A thrown error or malformed SVG produces
163
- `CanvasToSvgError`; it does not activate `canvasFallback`. A valid SVG that uses
164
- unsupported vector features follows the separate `fallback` policy.
142
+ On Vue 3.4 or earlier, use
143
+ `const report = ref<HTMLElement | null>(null)` with the same template ref and
144
+ pass `report.value` to `renderPdf()`.
165
145
 
166
- Scoped rasterization records `CSS_SUBTREE_RASTERIZED` or
167
- `CANVAS_SUBTREE_RASTERIZED`. Inspect diagnostics before describing output as
168
- fully vector.
146
+ ## Preview
169
147
 
170
- ### Pagination, metadata, cancellation, and progress
148
+ The preview renders the actual generated PDF inside your page. It uses isolated
149
+ Shadow DOM and canvas pages instead of an iframe, browser PDF plugin, or fake
150
+ HTML copy.
171
151
 
172
- `pageBreak.before`, `after`, and `avoid` accept selectors or selector arrays.
173
- `legacy` honors `.html2pdf__page-break`; `avoidAll` applies
174
- `break-inside: avoid` globally. These rules override computed snapshot defaults
175
- without overriding authored inline `!important` declarations.
152
+ ```ts
153
+ const pdf = await renderPdf(invoice);
154
+ const previewTarget = document.querySelector<HTMLElement>("#pdf-preview");
155
+ if (!previewTarget) throw new Error("Preview target not found");
176
156
 
177
- `metadata` accepts `title`, `author`, `subject`, `keywords`, and `creator`.
178
- `keywords` may be a string or an array.
157
+ const preview = await pdf.preview(previewTarget, {
158
+ initialScale: "fit-width",
159
+ });
179
160
 
180
- `signal` rejects at snapshot and render boundaries. It cannot preempt a
181
- synchronous WASM render already running. `onProgress` reports the coarse phases
182
- `snapshot`, `wasm`, and `complete`; it is not per-page progress.
161
+ // Later, when closing the preview:
162
+ preview.dispose();
163
+ pdf.dispose();
164
+ ```
183
165
 
184
- ## PDF output and preview
166
+ ## Page layouts
185
167
 
186
- `PdfDocument` exposes immutable output through:
168
+ Use the named `a4` and `letter` formats in portrait or landscape mode. A4
169
+ landscape works well for presentation decks:
187
170
 
188
- - `toUint8Array()`, `toArrayBuffer()`, and `toBlob()`;
189
- - `download(filename)`;
190
- - `createObjectURL()` and `revokeObjectURL(url)`;
191
- - `preview(target, options)`;
192
- - `pageCount` and `diagnostics`.
171
+ ```ts
172
+ const pdf = await renderPdf(slides, {
173
+ page: {
174
+ format: "a4",
175
+ orientation: "landscape",
176
+ unit: "mm",
177
+ margin: [12, 12],
178
+ },
179
+ });
180
+ ```
193
181
 
194
- Byte methods return defensive copies. `PdfDocument.dispose()` disposes every
195
- preview it owns, revokes tracked object URLs, and invalidates future exports.
196
- Manually revoke long-lived object URLs earlier when possible.
182
+ For postcards or any other size, pass custom `[width, height]` dimensions:
197
183
 
198
184
  ```ts
199
- const preview = await pdf.preview(document.querySelector("#preview")!, {
200
- initialScale: "fit-width",
201
- minScale: 0.25,
202
- maxScale: 3,
203
- zoomStep: 0.25,
204
- maxPixelRatio: 2,
205
- onProgress: (completed, total) => updatePreviewProgress(completed, total),
185
+ const pdf = await renderPdf(postcard, {
186
+ page: { format: [148, 105], unit: "mm", margin: 8 },
206
187
  });
207
-
208
- await preview.setScale(1.25);
209
- await preview.fitToWidth();
210
- preview.dispose();
211
188
  ```
212
189
 
213
- The preview renders every page into an isolated Shadow DOM canvas viewer. It
214
- does not use iframe, object, embed, or the browser PDF plugin.
190
+ ## Benchmark
215
191
 
216
- ## Diagnostics and errors
192
+ One recorded run of the deterministic 30-page stress report produced:
217
193
 
218
- Successful documents may contain structured diagnostics with a stable `code`,
219
- `severity`, and `message`, plus optional `property`, `nodePath`, `phase`, and
220
- `fallback`. Use `unsupportedCss: "error"`, `fallback: "error"`, and
221
- `resourcePolicy: "error"` when omissions must reject the operation.
194
+ | Engine | First PDF | Warm render | File size | Pages | Content model |
195
+ | --- | ---: | ---: | ---: | ---: | --- |
196
+ | `html2realpdf` | 1595.9 ms | 1451.2 ms | 441.1 kB | 30 | Native/selectable PDF |
197
+ | `html2pdf.js` | 2124.6 ms | 1952.4 ms | 3.11 MB | 30 | Raster image PDF |
222
198
 
223
- The package exports these error classes:
199
+ **Main differences versus html2pdf.js**
224
200
 
225
- - `Html2RealPdfError`, the base class with a machine-readable `code`;
226
- - `UnsupportedEnvironmentError`;
227
- - `InvalidSourceError`;
228
- - `UnsupportedCssError`;
229
- - `WasmRenderError`, including a native or bridge `status`;
230
- - `ResourceLoadError`;
231
- - `CanvasToSvgError`, including `nodePath`;
232
- - `UnsupportedCompatibilityFeatureError`.
201
+ - **33.1% faster first PDF**
202
+ - **34.5% faster warm render**
203
+ - **85.8% smaller file**
204
+ - and, of course, a REAL PDF 😏
233
205
 
234
- Cancellation normally rejects with `AbortError`. Invalid page margins produce a
235
- `RangeError`; lifecycle misuse after disposal produces a regular `Error`.
206
+ ## Contributing
236
207
 
237
- ## html2pdf.js compatibility
208
+ You need Zig `0.16.0`, Node.js `20.16+`, npm, and Make. On a fresh checkout,
209
+ install the JavaScript dependencies once:
238
210
 
239
- ```ts
240
- import html2pdf from "@imggion/html2realpdf";
241
-
242
- await html2pdf()
243
- .set({
244
- filename: "invoice.pdf",
245
- margin: [10, 12],
246
- pagebreak: { mode: ["css", "legacy"], avoid: ".line-item" },
247
- jsPDF: { format: "a4", unit: "mm", orientation: "portrait" },
248
- })
249
- .from(document.querySelector("#invoice")!)
250
- .save();
211
+ ```sh
212
+ npm ci --prefix bindings/js
213
+ npm ci --prefix tests/react
214
+ npm ci --prefix tests/web
251
215
  ```
252
216
 
253
- | Compatibility surface | Status |
217
+ | Command | Purpose |
254
218
  | --- | --- |
255
- | `from(string | Element | ref)` | Supported |
256
- | `set`, `using` | Supported for typed PDF options |
257
- | `toPdf`, `save`, `saveAs` | Supported |
258
- | `outputPdf`, `output`, `export` | Blob, ArrayBuffer, Blob URL, and data URL supported |
259
- | `get`, Promise-like chaining | Supported |
260
- | `toContainer` | Chain-preserving no-op; no intermediate container is exposed |
261
- | `to("container")` | Schedules PDF output directly |
262
- | Canvas or image input stages | Unsupported |
263
- | `toCanvas`, `toImg`, `outputImg` | Throw `UnsupportedCompatibilityFeatureError` |
264
- | `html2canvas` and raster `image` options | Rejected explicitly |
265
-
266
- Passing a source directly to `html2pdf(source, options)` also schedules `save`,
267
- matching the shorthand compatibility behavior.
268
-
269
- Blob URL outputs remain owned by the cached `PdfDocument`. Retrieve it with
270
- `await worker.get("pdf")` to revoke an individual URL or dispose the document.
271
-
272
- ## Runtime and licensing
219
+ | `make test` | Run the Zig and renderer tests |
220
+ | `make release` | Build the native release binary |
221
+ | `make wasm` | Build the default `ReleaseFast` WebAssembly and browser package |
222
+ | `make wasm-small` | Build the optional size-oriented `ReleaseSmall` package asset |
223
+ | `make react` | Start the React integration app |
224
+ | `make test-release` | Run the complete release gate |
273
225
 
274
- - Rendering requires a browser with DOM, WebAssembly, Worker, and Blob support.
275
- - Node.js `20.16+` is required for package build tooling, not browser rendering.
276
- - Project code is MIT licensed. `dist/LICENSE.md` contains the consolidated
277
- project and third-party license inventory.
278
-
279
- ## Share without the npm registry
280
-
281
- Run `npm pack` from this package directory and send the generated
282
- `imggion-html2realpdf-0.1.0.tgz` file. A consumer can install it with:
226
+ To open the small browser test harness:
283
227
 
284
228
  ```sh
285
- npm install ./imggion-html2realpdf-0.1.0.tgz
286
- # or
287
- pnpm add ./imggion-html2realpdf-0.1.0.tgz
288
- # or
289
- yarn add file:./imggion-html2realpdf-0.1.0.tgz
229
+ make wasm
230
+ python3 -m http.server 8765
290
231
  ```
291
232
 
292
- The packaged model instructions live at `skills/html2realpdf/SKILL.md`.
233
+ Visit [http://localhost:8765/tests/web/index.html](http://localhost:8765/tests/web/index.html).
234
+
235
+ ## License
236
+
237
+ The project code is released under the MIT License. See [LICENSE.md](LICENSE.md)
238
+ for the complete project and third-party license inventory.
package/dist/errors.js CHANGED
@@ -11,25 +11,28 @@ export class Html2RealPdfError extends Error {
11
11
  code, options) {
12
12
  super(message, options);
13
13
  this.code = code;
14
- this.name = new.target.name;
14
+ this.name = "Html2RealPdfError";
15
15
  }
16
16
  }
17
17
  /** Rendering was requested where browser DOM APIs are unavailable. */
18
18
  export class UnsupportedEnvironmentError extends Html2RealPdfError {
19
19
  constructor(message = "html2realpdf rendering requires a browser environment") {
20
20
  super(message, "UNSUPPORTED_ENVIRONMENT");
21
+ this.name = "UnsupportedEnvironmentError";
21
22
  }
22
23
  }
23
24
  /** The source is not a string, mounted element, or non-null ref-like object. */
24
25
  export class InvalidSourceError extends Html2RealPdfError {
25
26
  constructor(message) {
26
27
  super(message, "INVALID_SOURCE");
28
+ this.name = "InvalidSourceError";
27
29
  }
28
30
  }
29
31
  /** Authored CSS or SVG cannot satisfy the selected strictness policy. */
30
32
  export class UnsupportedCssError extends Html2RealPdfError {
31
33
  constructor(message) {
32
34
  super(message, "UNSUPPORTED_CSS");
35
+ this.name = "UnsupportedCssError";
33
36
  }
34
37
  }
35
38
  /**
@@ -46,12 +49,14 @@ export class WasmRenderError extends Html2RealPdfError {
46
49
  status, options) {
47
50
  super(message, "WASM_RENDER_FAILED", options);
48
51
  this.status = status;
52
+ this.name = "WasmRenderError";
49
53
  }
50
54
  }
51
55
  /** An image, stylesheet, canvas, or SVG resource could not be materialized. */
52
56
  export class ResourceLoadError extends Html2RealPdfError {
53
57
  constructor(resource, options) {
54
58
  super(`Could not load resource: ${resource}`, "RESOURCE_LOAD_FAILED", options);
59
+ this.name = "ResourceLoadError";
55
60
  }
56
61
  }
57
62
  /** A canvas-to-SVG adapter threw or returned an invalid result. */
@@ -62,12 +67,14 @@ export class CanvasToSvgError extends Html2RealPdfError {
62
67
  nodePath, options) {
63
68
  super(`${message}: ${nodePath}`, "CANVAS_TO_SVG_FAILED", options);
64
69
  this.nodePath = nodePath;
70
+ this.name = "CanvasToSvgError";
65
71
  }
66
72
  }
67
73
  /** A requested html2pdf.js stage belongs to its unsupported raster pipeline. */
68
74
  export class UnsupportedCompatibilityFeatureError extends Html2RealPdfError {
69
75
  constructor(feature) {
70
76
  super(`${feature} belongs to the raster html2canvas/jsPDF pipeline and is not supported`, "UNSUPPORTED_COMPAT_FEATURE");
77
+ this.name = "UnsupportedCompatibilityFeatureError";
71
78
  }
72
79
  }
73
80
  //# sourceMappingURL=errors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,iEAAiE;AACjE,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAI/B,IAAI;IAHf,YACE,OAAe;IACf,4DAA4D;IACnD,IAAY,EACrB,OAAsB;QAEtB,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;oBAHf,IAAI;QAIb,IAAI,CAAC,IAAI,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC;IAC9B,CAAC;CACF;AAED,sEAAsE;AACtE,MAAM,OAAO,2BAA4B,SAAQ,iBAAiB;IAChE,YAAY,OAAO,GAAG,uDAAuD;QAC3E,KAAK,CAAC,OAAO,EAAE,yBAAyB,CAAC,CAAC;IAC5C,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,OAAO,kBAAmB,SAAQ,iBAAiB;IACvD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAC;IACnC,CAAC;CACF;AAED,yEAAyE;AACzE,MAAM,OAAO,mBAAoB,SAAQ,iBAAiB;IACxD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;IACpC,CAAC;CACF;AAED;;;;;;GAMG;AACH,MAAM,OAAO,eAAgB,SAAQ,iBAAiB;IAIzC,MAAM;IAHjB,YACE,OAAe;IACf,0DAA0D;IACjD,MAAc,EACvB,OAAsB;QAEtB,KAAK,CAAC,OAAO,EAAE,oBAAoB,EAAE,OAAO,CAAC,CAAC;sBAHrC,MAAM;IAIjB,CAAC;CACF;AAED,+EAA+E;AAC/E,MAAM,OAAO,iBAAkB,SAAQ,iBAAiB;IACtD,YAAY,QAAgB,EAAE,OAAsB;QAClD,KAAK,CAAC,4BAA4B,QAAQ,EAAE,EAAE,sBAAsB,EAAE,OAAO,CAAC,CAAC;IACjF,CAAC;CACF;AAED,mEAAmE;AACnE,MAAM,OAAO,gBAAiB,SAAQ,iBAAiB;IAI1C,QAAQ;IAHnB,YACE,OAAe;IACf,wDAAwD;IAC/C,QAAgB,EACzB,OAAsB;QAEtB,KAAK,CAAC,GAAG,OAAO,KAAK,QAAQ,EAAE,EAAE,sBAAsB,EAAE,OAAO,CAAC,CAAC;wBAHzD,QAAQ;IAInB,CAAC;CACF;AAED,gFAAgF;AAChF,MAAM,OAAO,oCAAqC,SAAQ,iBAAiB;IACzE,YAAY,OAAe;QACzB,KAAK,CAAC,GAAG,OAAO,wEAAwE,EAAE,4BAA4B,CAAC,CAAC;IAC1H,CAAC;CACF","sourcesContent":["/**\n * Stable error classes exposed by the package root.\n *\n * @packageDocumentation\n */\n\n/** Base error carrying a machine-readable wrapper error code. */\nexport class Html2RealPdfError extends Error {\n constructor(\n message: string,\n /** Stable value suitable for control flow and telemetry. */\n readonly code: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = new.target.name;\n }\n}\n\n/** Rendering was requested where browser DOM APIs are unavailable. */\nexport class UnsupportedEnvironmentError extends Html2RealPdfError {\n constructor(message = \"html2realpdf rendering requires a browser environment\") {\n super(message, \"UNSUPPORTED_ENVIRONMENT\");\n }\n}\n\n/** The source is not a string, mounted element, or non-null ref-like object. */\nexport class InvalidSourceError extends Html2RealPdfError {\n constructor(message: string) {\n super(message, \"INVALID_SOURCE\");\n }\n}\n\n/** Authored CSS or SVG cannot satisfy the selected strictness policy. */\nexport class UnsupportedCssError extends Html2RealPdfError {\n constructor(message: string) {\n super(message, \"UNSUPPORTED_CSS\");\n }\n}\n\n/**\n * The WASM bridge or native renderer failed.\n *\n * @remarks\n * `status` preserves the native or bridge status code for logging and\n * operational classification.\n */\nexport class WasmRenderError extends Html2RealPdfError {\n constructor(\n message: string,\n /** Native renderer status or a negative bridge status. */\n readonly status: number,\n options?: ErrorOptions,\n ) {\n super(message, \"WASM_RENDER_FAILED\", options);\n }\n}\n\n/** An image, stylesheet, canvas, or SVG resource could not be materialized. */\nexport class ResourceLoadError extends Html2RealPdfError {\n constructor(resource: string, options?: ErrorOptions) {\n super(`Could not load resource: ${resource}`, \"RESOURCE_LOAD_FAILED\", options);\n }\n}\n\n/** A canvas-to-SVG adapter threw or returned an invalid result. */\nexport class CanvasToSvgError extends Html2RealPdfError {\n constructor(\n message: string,\n /** Snapshot path of the canvas whose adapter failed. */\n readonly nodePath: string,\n options?: ErrorOptions,\n ) {\n super(`${message}: ${nodePath}`, \"CANVAS_TO_SVG_FAILED\", options);\n }\n}\n\n/** A requested html2pdf.js stage belongs to its unsupported raster pipeline. */\nexport class UnsupportedCompatibilityFeatureError extends Html2RealPdfError {\n constructor(feature: string) {\n super(`${feature} belongs to the raster html2canvas/jsPDF pipeline and is not supported`, \"UNSUPPORTED_COMPAT_FEATURE\");\n }\n}\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,iEAAiE;AACjE,MAAM,OAAO,iBAAkB,SAAQ,KAAK;IAI/B,IAAI;IAHf,YACE,OAAe;IACf,4DAA4D;IACnD,IAAY,EACrB,OAAsB;QAEtB,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;oBAHf,IAAI;QAIb,IAAI,CAAC,IAAI,GAAG,mBAAmB,CAAC;IAClC,CAAC;CACF;AAED,sEAAsE;AACtE,MAAM,OAAO,2BAA4B,SAAQ,iBAAiB;IAChE,YAAY,OAAO,GAAG,uDAAuD;QAC3E,KAAK,CAAC,OAAO,EAAE,yBAAyB,CAAC,CAAC;QAC1C,IAAI,CAAC,IAAI,GAAG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qC,SAAQ,iBAAiB;IACzE,YAAY,OAAe;QACzB,KAAK,CAAC,GAAG,OAAO,wEAAwE,EAAE,4BAA4B,CAAC,CAAC;QACxH,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF","sourcesContent":["/**\n * Stable error classes exposed by the package root.\n *\n * @packageDocumentation\n */\n\n/** Base error carrying a machine-readable wrapper error code. */\nexport class Html2RealPdfError extends Error {\n constructor(\n message: string,\n /** Stable value suitable for control flow and telemetry. */\n readonly code: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = \"Html2RealPdfError\";\n }\n}\n\n/** Rendering was requested where browser DOM APIs are unavailable. */\nexport class UnsupportedEnvironmentError extends Html2RealPdfError {\n constructor(message = \"html2realpdf rendering requires a browser environment\") {\n super(message, \"UNSUPPORTED_ENVIRONMENT\");\n this.name = \"UnsupportedEnvironmentError\";\n }\n}\n\n/** The source is not a string, mounted element, or non-null ref-like object. */\nexport class InvalidSourceError extends Html2RealPdfError {\n constructor(message: string) {\n super(message, \"INVALID_SOURCE\");\n this.name = \"InvalidSourceError\";\n }\n}\n\n/** Authored CSS or SVG cannot satisfy the selected strictness policy. */\nexport class UnsupportedCssError extends Html2RealPdfError {\n constructor(message: string) {\n super(message, \"UNSUPPORTED_CSS\");\n this.name = \"UnsupportedCssError\";\n }\n}\n\n/**\n * The WASM bridge or native renderer failed.\n *\n * @remarks\n * `status` preserves the native or bridge status code for logging and\n * operational classification.\n */\nexport class WasmRenderError extends Html2RealPdfError {\n constructor(\n message: string,\n /** Native renderer status or a negative bridge status. */\n readonly status: number,\n options?: ErrorOptions,\n ) {\n super(message, \"WASM_RENDER_FAILED\", options);\n this.name = \"WasmRenderError\";\n }\n}\n\n/** An image, stylesheet, canvas, or SVG resource could not be materialized. */\nexport class ResourceLoadError extends Html2RealPdfError {\n constructor(resource: string, options?: ErrorOptions) {\n super(`Could not load resource: ${resource}`, \"RESOURCE_LOAD_FAILED\", options);\n this.name = \"ResourceLoadError\";\n }\n}\n\n/** A canvas-to-SVG adapter threw or returned an invalid result. */\nexport class CanvasToSvgError extends Html2RealPdfError {\n constructor(\n message: string,\n /** Snapshot path of the canvas whose adapter failed. */\n readonly nodePath: string,\n options?: ErrorOptions,\n ) {\n super(`${message}: ${nodePath}`, \"CANVAS_TO_SVG_FAILED\", options);\n this.name = \"CanvasToSvgError\";\n }\n}\n\n/** A requested html2pdf.js stage belongs to its unsupported raster pipeline. */\nexport class UnsupportedCompatibilityFeatureError extends Html2RealPdfError {\n constructor(feature: string) {\n super(`${feature} belongs to the raster html2canvas/jsPDF pipeline and is not supported`, \"UNSUPPORTED_COMPAT_FEATURE\");\n this.name = \"UnsupportedCompatibilityFeatureError\";\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -9,6 +9,6 @@ export default html2pdf;
9
9
  export { CompatWorker } from "./compat.js";
10
10
  export * from "./errors.js";
11
11
  export { PdfDocument } from "./pdf-document.js";
12
- export { PdfPreview, type PdfPreviewOptions } from "./preview.js";
12
+ export { PdfPreview, type PdfPreviewOptions, type PdfPreviewTheme } from "./preview.js";
13
13
  export { createRenderer, Html2RealPdf, renderPdf } from "./renderer.js";
14
14
  export type * from "./types.js";
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,QAAQ,MAAM,aAAa,CAAC;AAEnC,eAAe,QAAQ,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,UAAU,EAA0B,MAAM,cAAc,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC","sourcesContent":["/**\n * Browser-first HTML-to-PDF rendering with selectable text, native vectors,\n * typed configuration, and an html2pdf.js compatibility layer.\n *\n * @packageDocumentation\n */\nimport html2pdf from \"./compat.js\";\n\nexport default html2pdf;\nexport { CompatWorker } from \"./compat.js\";\nexport * from \"./errors.js\";\nexport { PdfDocument } from \"./pdf-document.js\";\nexport { PdfPreview, type PdfPreviewOptions } from \"./preview.js\";\nexport { createRenderer, Html2RealPdf, renderPdf } from \"./renderer.js\";\nexport type * from \"./types.js\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,QAAQ,MAAM,aAAa,CAAC;AAEnC,eAAe,QAAQ,CAAC;AACxB,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,cAAc,aAAa,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAgD,MAAM,cAAc,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC","sourcesContent":["/**\n * Browser-first HTML-to-PDF rendering with selectable text, native vectors,\n * typed configuration, and an html2pdf.js compatibility layer.\n *\n * @packageDocumentation\n */\nimport html2pdf from \"./compat.js\";\n\nexport default html2pdf;\nexport { CompatWorker } from \"./compat.js\";\nexport * from \"./errors.js\";\nexport { PdfDocument } from \"./pdf-document.js\";\nexport { PdfPreview, type PdfPreviewOptions, type PdfPreviewTheme } from \"./preview.js\";\nexport { createRenderer, Html2RealPdf, renderPdf } from \"./renderer.js\";\nexport type * from \"./types.js\";\n"]}
package/dist/preview.d.ts CHANGED
@@ -3,8 +3,14 @@
3
3
  *
4
4
  * @packageDocumentation
5
5
  */
6
+ /** Color theme used by the integrated PDF preview controls. */
7
+ export type PdfPreviewTheme = "system" | "light" | "dark";
6
8
  /** Display and rendering limits for `PdfDocument.preview`. */
7
9
  export interface PdfPreviewOptions {
10
+ /** Whether to show the page summary and zoom toolbar. Defaults to `true`. */
11
+ showToolbar?: boolean;
12
+ /** Padding around the rendered pages in CSS pixels. Defaults to `28`, or `16` on narrow screens. */
13
+ padding?: number;
8
14
  /** Initial zoom or automatic fit. Defaults to `fit-width`. */
9
15
  initialScale?: number | "fit-width";
10
16
  /** Lowest permitted zoom. Defaults to `0.25` and is never below `0.1`. */
@@ -17,6 +23,8 @@ export interface PdfPreviewOptions {
17
23
  maxPixelRatio?: number;
18
24
  /** Accessible label for the preview region. Defaults to `PDF preview`. */
19
25
  ariaLabel?: string;
26
+ /** Preview-control theme. Defaults to `system` and follows the browser preference. */
27
+ theme?: PdfPreviewTheme;
20
28
  /** Called after each page canvas completes rendering. */
21
29
  onProgress?: (completedPages: number, totalPages: number) => void;
22
30
  }
@@ -55,6 +63,10 @@ export declare class PdfPreview {
55
63
  private constructor();
56
64
  /** Current logical PDF.js scale after option clamping. */
57
65
  get currentScale(): number;
66
+ /** Current preview-control theme, including the default `system` mode. */
67
+ get currentTheme(): PdfPreviewTheme;
68
+ /** Updates the preview-control theme without rerendering the PDF pages. */
69
+ setTheme(theme: PdfPreviewTheme): void;
58
70
  /** Sets a clamped scale and rerenders every page canvas. */
59
71
  setScale(value: number): Promise<void>;
60
72
  /** Fits the first page to the available viewer width and rerenders all pages. */
@@ -68,6 +80,7 @@ export declare class PdfPreview {
68
80
  */
69
81
  private renderPages;
70
82
  private updateControls;
83
+ private availablePageWidth;
71
84
  private showError;
72
85
  private releaseDocument;
73
86
  private assertActive;
package/dist/preview.js CHANGED
@@ -5,7 +5,17 @@
5
5
  */
6
6
  const VIEWER_STYLES = `
7
7
  :host {
8
+ --preview-scale: #33404d;
9
+ --preview-summary: #52606d;
10
+ --preview-focus: #111;
11
+ --preview-toolbar: rgba(255, 255, 255, 0.96);
12
+ --preview-toolbar-line: rgba(24, 32, 42, 0.10);
13
+ --preview-zoom: #fff;
14
+ --preview-zoom-hover: #f5f7fa;
15
+ --preview-zoom-ink: #18202a;
16
+ --preview-zoom-line: rgba(24, 32, 42, 0.16);
8
17
  color: #18202a;
18
+ color-scheme: light dark;
9
19
  display: block;
10
20
  font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
11
21
  -webkit-font-smoothing: antialiased;
@@ -22,38 +32,40 @@ const VIEWER_STYLES = `
22
32
  min-height: 520px;
23
33
  overflow: hidden;
24
34
  }
35
+ .viewer.toolbar-hidden { grid-template-rows: minmax(320px, 1fr); }
25
36
  .toolbar {
26
37
  align-items: center;
27
- background: rgba(255, 255, 255, 0.96);
28
- box-shadow: 0 1px 0 rgba(24, 32, 42, 0.10);
38
+ background: var(--preview-toolbar);
39
+ box-shadow: 0 1px 0 var(--preview-toolbar-line);
29
40
  display: flex;
30
41
  gap: 8px;
31
42
  justify-content: space-between;
32
43
  min-height: 60px;
33
44
  padding: 8px 12px;
34
45
  }
46
+ .toolbar[hidden] { display: none; }
35
47
  .summary {
36
- color: #52606d;
48
+ color: var(--preview-summary);
37
49
  font-size: 13px;
38
50
  font-variant-numeric: tabular-nums;
39
51
  min-width: 9rem;
40
52
  }
41
53
  .controls { align-items: center; display: flex; gap: 6px; }
42
54
  .zoom {
43
- background: #fff;
55
+ background: var(--preview-zoom);
44
56
  border: 0;
45
57
  border-radius: 9px;
46
- box-shadow: 0 0 0 1px rgba(24, 32, 42, 0.16);
47
- color: #18202a;
58
+ box-shadow: 0 0 0 1px var(--preview-zoom-line);
59
+ color: var(--preview-zoom-ink);
48
60
  cursor: pointer;
49
61
  min-height: 44px;
50
62
  min-width: 44px;
51
63
  padding: 0 12px;
52
64
  }
53
- .zoom:focus-visible { outline: 2px solid #111; outline-offset: 2px; }
65
+ .zoom:focus-visible { outline: 2px solid var(--preview-focus); outline-offset: 2px; }
54
66
  .zoom:disabled { cursor: not-allowed; opacity: 0.42; }
55
67
  .scale {
56
- color: #33404d;
68
+ color: var(--preview-scale);
57
69
  font-size: 13px;
58
70
  font-variant-numeric: tabular-nums;
59
71
  min-width: 3.75rem;
@@ -86,7 +98,44 @@ const VIEWER_STYLES = `
86
98
  text-align: center;
87
99
  }
88
100
  @media (hover: hover) and (pointer: fine) {
89
- .zoom:not(:disabled):hover { background: #f5f7fa; }
101
+ .zoom:not(:disabled):hover { background: var(--preview-zoom-hover); }
102
+ }
103
+ @media (prefers-color-scheme: dark) {
104
+ :host {
105
+ --preview-scale: #d7dee7;
106
+ --preview-summary: #b7c0ca;
107
+ --preview-focus: #fff;
108
+ --preview-toolbar: rgba(24, 32, 42, 0.96);
109
+ --preview-toolbar-line: rgba(255, 255, 255, 0.12);
110
+ --preview-zoom: #26313c;
111
+ --preview-zoom-hover: #303c48;
112
+ --preview-zoom-ink: #f8fafc;
113
+ --preview-zoom-line: rgba(255, 255, 255, 0.18);
114
+ }
115
+ }
116
+ :host([data-theme="light"]) {
117
+ --preview-scale: #33404d;
118
+ --preview-summary: #52606d;
119
+ --preview-focus: #111;
120
+ --preview-toolbar: rgba(255, 255, 255, 0.96);
121
+ --preview-toolbar-line: rgba(24, 32, 42, 0.10);
122
+ --preview-zoom: #fff;
123
+ --preview-zoom-hover: #f5f7fa;
124
+ --preview-zoom-ink: #18202a;
125
+ --preview-zoom-line: rgba(24, 32, 42, 0.16);
126
+ color-scheme: light;
127
+ }
128
+ :host([data-theme="dark"]) {
129
+ --preview-scale: #d7dee7;
130
+ --preview-summary: #b7c0ca;
131
+ --preview-focus: #fff;
132
+ --preview-toolbar: rgba(24, 32, 42, 0.96);
133
+ --preview-toolbar-line: rgba(255, 255, 255, 0.12);
134
+ --preview-zoom: #26313c;
135
+ --preview-zoom-hover: #303c48;
136
+ --preview-zoom-ink: #f8fafc;
137
+ --preview-zoom-line: rgba(255, 255, 255, 0.18);
138
+ color-scheme: dark;
90
139
  }
91
140
  @media (max-width: 560px) {
92
141
  .viewer { border-radius: 10px; min-height: 440px; }
@@ -155,6 +204,7 @@ export class PdfPreview {
155
204
  this.onProgress = options.onProgress;
156
205
  this.element = document.createElement("div");
157
206
  this.element.dataset.html2realpdfPreview = "";
207
+ this.setTheme(options.theme ?? "system");
158
208
  this.shadow = this.element.attachShadow({ mode: "open" });
159
209
  const style = document.createElement("style");
160
210
  style.textContent = VIEWER_STYLES;
@@ -164,6 +214,9 @@ export class PdfPreview {
164
214
  viewer.setAttribute("aria-label", options.ariaLabel ?? "PDF preview");
165
215
  const toolbar = document.createElement("div");
166
216
  toolbar.className = "toolbar";
217
+ toolbar.hidden = options.showToolbar === false;
218
+ if (toolbar.hidden)
219
+ viewer.classList.add("toolbar-hidden");
167
220
  this.summaryElement = document.createElement("div");
168
221
  this.summaryElement.className = "summary";
169
222
  this.summaryElement.setAttribute("aria-live", "polite");
@@ -180,6 +233,9 @@ export class PdfPreview {
180
233
  toolbar.append(this.summaryElement, controls);
181
234
  this.pagesElement = document.createElement("div");
182
235
  this.pagesElement.className = "pages";
236
+ if (options.padding !== undefined && Number.isFinite(options.padding)) {
237
+ this.pagesElement.style.padding = `${Math.max(options.padding, 0)}px`;
238
+ }
183
239
  this.pagesElement.tabIndex = 0;
184
240
  this.pagesElement.setAttribute("aria-label", "PDF pages");
185
241
  viewer.append(toolbar, this.pagesElement);
@@ -214,6 +270,18 @@ export class PdfPreview {
214
270
  get currentScale() {
215
271
  return this.scale;
216
272
  }
273
+ /** Current preview-control theme, including the default `system` mode. */
274
+ get currentTheme() {
275
+ return this.element.dataset.theme;
276
+ }
277
+ /** Updates the preview-control theme without rerendering the PDF pages. */
278
+ setTheme(theme) {
279
+ this.assertActive();
280
+ if (theme !== "system" && theme !== "light" && theme !== "dark") {
281
+ throw new TypeError(`Unsupported PDF preview theme: ${String(theme)}`);
282
+ }
283
+ this.element.dataset.theme = theme;
284
+ }
217
285
  /** Sets a clamped scale and rerenders every page canvas. */
218
286
  async setScale(value) {
219
287
  this.assertActive();
@@ -232,8 +300,7 @@ export class PdfPreview {
232
300
  const firstPage = await pdf.getPage(1);
233
301
  const viewport = firstPage.getViewport({ scale: 1 });
234
302
  firstPage.cleanup();
235
- const availableWidth = Math.max(this.pagesElement.clientWidth - 56, 120);
236
- this.scale = clamp(availableWidth / viewport.width, this.minScale, this.maxScale);
303
+ this.scale = clamp(this.availablePageWidth() / viewport.width, this.minScale, this.maxScale);
237
304
  await this.renderPages();
238
305
  }
239
306
  /** Cancels active work, destroys PDF.js state, and clears the target. */
@@ -262,8 +329,7 @@ export class PdfPreview {
262
329
  const firstPage = await this.document.getPage(1);
263
330
  const viewport = firstPage.getViewport({ scale: 1 });
264
331
  firstPage.cleanup();
265
- const availableWidth = Math.max(this.pagesElement.clientWidth - 56, 120);
266
- this.scale = clamp(availableWidth / viewport.width, this.minScale, this.maxScale);
332
+ this.scale = clamp(this.availablePageWidth() / viewport.width, this.minScale, this.maxScale);
267
333
  }
268
334
  else {
269
335
  this.scale = clamp(initialScale, this.minScale, this.maxScale);
@@ -331,6 +397,11 @@ export class PdfPreview {
331
397
  this.zoomOutButton.disabled = this.scale <= this.minScale + 0.001;
332
398
  this.zoomInButton.disabled = this.scale >= this.maxScale - 0.001;
333
399
  }
400
+ availablePageWidth() {
401
+ const style = getComputedStyle(this.pagesElement);
402
+ const horizontalPadding = Number.parseFloat(style.paddingLeft) + Number.parseFloat(style.paddingRight);
403
+ return Math.max(this.pagesElement.clientWidth - horizontalPadding, 120);
404
+ }
334
405
  showError(error) {
335
406
  if (this.disposed)
336
407
  return;
@@ -1 +1 @@
1
- {"version":3,"file":"preview.js","sourceRoot":"","sources":["../src/preview.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAwDH,MAAM,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4FrB,CAAC;AAEF,IAAI,WAA6C,CAAC;AAElD,sFAAsF;AACtF,KAAK,UAAU,SAAS;IACtB,WAAW,KAAK,MAAM,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC,sBAAsB,EAAE,OAAO,IAAI,CAAC,GAAG,CAA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AC;IACrE,CAAC;CACF;AAED,SAAS,YAAY,CAAC,KAAa,EAAE,SAAiB;IACpD,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChD,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC;IAC1B,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC;IACvB,MAAM,CAAC,WAAW,GAAG,KAAK,CAAC;IAC3B,MAAM,CAAC,YAAY,CAAC,YAAY,EAAE,SAAS,CAAC,CAAC;IAC7C,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,KAAK,CAAC,KAAa,EAAE,OAAe,EAAE,OAAe;IAC5D,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * Shadow-DOM PDF preview backed by package-relative PDF.js assets.\n *\n * @packageDocumentation\n */\n\n/** Display and rendering limits for `PdfDocument.preview`. */\nexport interface PdfPreviewOptions {\n /** Initial zoom or automatic fit. Defaults to `fit-width`. */\n initialScale?: number | \"fit-width\";\n /** Lowest permitted zoom. Defaults to `0.25` and is never below `0.1`. */\n minScale?: number;\n /** Highest permitted zoom. Defaults to `3` and is never below `minScale`. */\n maxScale?: number;\n /** Zoom-button increment. Defaults to `0.25` and is never below `0.05`. */\n zoomStep?: number;\n /** Device-pixel-ratio cap used for page canvases. Defaults to `2`. */\n maxPixelRatio?: number;\n /** Accessible label for the preview region. Defaults to `PDF preview`. */\n ariaLabel?: string;\n /** Called after each page canvas completes rendering. */\n onProgress?: (completedPages: number, totalPages: number) => void;\n}\n\ninterface PdfJsViewport {\n readonly width: number;\n readonly height: number;\n}\n\ninterface PdfJsRenderTask {\n readonly promise: Promise<void>;\n cancel(): void;\n}\n\ninterface PdfJsPage {\n getViewport(options: { scale: number }): PdfJsViewport;\n render(options: {\n canvas: HTMLCanvasElement;\n viewport: PdfJsViewport;\n transform?: readonly [number, number, number, number, number, number];\n }): PdfJsRenderTask;\n cleanup(): void;\n}\n\ninterface PdfJsDocument {\n readonly numPages: number;\n getPage(pageNumber: number): Promise<PdfJsPage>;\n destroy(): Promise<void>;\n}\n\ninterface PdfJsLoadingTask {\n readonly promise: Promise<PdfJsDocument>;\n destroy(): Promise<void>;\n}\n\ninterface PdfJsModule {\n readonly GlobalWorkerOptions: { workerSrc: string };\n getDocument(options: { data: Uint8Array }): PdfJsLoadingTask;\n}\n\nconst VIEWER_STYLES = `\n :host {\n color: #18202a;\n display: block;\n font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n -webkit-font-smoothing: antialiased;\n }\n *, *::before, *::after { box-sizing: border-box; }\n button { font: inherit; touch-action: manipulation; }\n .viewer {\n background: #e9edf2;\n border-radius: 14px;\n box-shadow: 0 0 0 1px rgba(24, 32, 42, 0.12), 0 18px 50px rgba(24, 32, 42, 0.10);\n display: grid;\n grid-template-rows: auto minmax(320px, 1fr);\n isolation: isolate;\n min-height: 520px;\n overflow: hidden;\n }\n .toolbar {\n align-items: center;\n background: rgba(255, 255, 255, 0.96);\n box-shadow: 0 1px 0 rgba(24, 32, 42, 0.10);\n display: flex;\n gap: 8px;\n justify-content: space-between;\n min-height: 60px;\n padding: 8px 12px;\n }\n .summary {\n color: #52606d;\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n min-width: 9rem;\n }\n .controls { align-items: center; display: flex; gap: 6px; }\n .zoom {\n background: #fff;\n border: 0;\n border-radius: 9px;\n box-shadow: 0 0 0 1px rgba(24, 32, 42, 0.16);\n color: #18202a;\n cursor: pointer;\n min-height: 44px;\n min-width: 44px;\n padding: 0 12px;\n }\n .zoom:focus-visible { outline: 2px solid #111; outline-offset: 2px; }\n .zoom:disabled { cursor: not-allowed; opacity: 0.42; }\n .scale {\n color: #33404d;\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n min-width: 3.75rem;\n text-align: center;\n }\n .pages {\n align-items: center;\n display: flex;\n flex-direction: column;\n gap: 24px;\n overflow: auto;\n overscroll-behavior: contain;\n padding: 28px;\n }\n .page {\n background: #fff;\n box-shadow: 0 0 0 1px rgba(24, 32, 42, 0.10), 0 10px 30px rgba(24, 32, 42, 0.14);\n flex: 0 0 auto;\n line-height: 0;\n }\n canvas { display: block; }\n .error {\n align-self: center;\n color: #9f1239;\n font-size: 14px;\n line-height: 1.5;\n margin: auto;\n max-width: 36rem;\n padding: 32px;\n text-align: center;\n }\n @media (hover: hover) and (pointer: fine) {\n .zoom:not(:disabled):hover { background: #f5f7fa; }\n }\n @media (max-width: 560px) {\n .viewer { border-radius: 10px; min-height: 440px; }\n .toolbar { align-items: flex-start; flex-direction: column; }\n .controls { width: 100%; }\n .controls .zoom:last-child { margin-left: auto; }\n .pages { gap: 16px; padding: 16px; }\n }\n`;\n\nlet pdfJsModule: Promise<PdfJsModule> | undefined;\n\n/** Lazily loads one shared PDF.js module while keeping preview assets relocatable. */\nasync function loadPdfJs(): Promise<PdfJsModule> {\n pdfJsModule ??= import(/* @vite-ignore */ new URL(\"./vendor/pdf.min.mjs\", import.meta.url).href)\n .then((module: unknown) => {\n const pdfJs = module as PdfJsModule;\n pdfJs.GlobalWorkerOptions.workerSrc = new URL(\"./vendor/pdf.worker.min.mjs\", import.meta.url).href;\n return pdfJs;\n })\n .catch((error: unknown) => {\n pdfJsModule = undefined;\n throw error;\n });\n return pdfJsModule;\n}\n\n/**\n * Interactive canvas preview created and owned by a `PdfDocument`.\n *\n * @remarks\n * The viewer replaces the target's children with one isolated Shadow DOM\n * subtree. Dispose it to cancel rendering, destroy PDF.js state, and clear the\n * target. Construct previews through `PdfDocument.preview`.\n */\nexport class PdfPreview {\n /** Host element inserted into the preview target. */\n readonly element: HTMLElement;\n\n private readonly shadow: ShadowRoot;\n private readonly pagesElement: HTMLElement;\n private readonly summaryElement: HTMLElement;\n private readonly scaleElement: HTMLOutputElement;\n private readonly zoomOutButton: HTMLButtonElement;\n private readonly zoomInButton: HTMLButtonElement;\n private readonly minScale: number;\n private readonly maxScale: number;\n private readonly zoomStep: number;\n private readonly pixelRatio: number;\n private readonly onProgress: ((completedPages: number, totalPages: number) => void) | undefined;\n private loadingTask: PdfJsLoadingTask | undefined;\n private document: PdfJsDocument | undefined;\n private renderTask: PdfJsRenderTask | undefined;\n private scale = 1;\n private renderVersion = 0;\n private disposed = false;\n\n private constructor(\n private readonly target: HTMLElement,\n private readonly bytes: Uint8Array,\n private readonly expectedPageCount: number,\n options: PdfPreviewOptions,\n private readonly onDispose?: () => void,\n ) {\n this.minScale = Math.max(options.minScale ?? 0.25, 0.1);\n this.maxScale = Math.max(options.maxScale ?? 3, this.minScale);\n this.zoomStep = Math.max(options.zoomStep ?? 0.25, 0.05);\n this.pixelRatio = Math.min(Math.max(window.devicePixelRatio || 1, 1), options.maxPixelRatio ?? 2);\n this.onProgress = options.onProgress;\n\n this.element = document.createElement(\"div\");\n this.element.dataset.html2realpdfPreview = \"\";\n this.shadow = this.element.attachShadow({ mode: \"open\" });\n\n const style = document.createElement(\"style\");\n style.textContent = VIEWER_STYLES;\n const viewer = document.createElement(\"section\");\n viewer.className = \"viewer\";\n viewer.setAttribute(\"role\", \"region\");\n viewer.setAttribute(\"aria-label\", options.ariaLabel ?? \"PDF preview\");\n\n const toolbar = document.createElement(\"div\");\n toolbar.className = \"toolbar\";\n this.summaryElement = document.createElement(\"div\");\n this.summaryElement.className = \"summary\";\n this.summaryElement.setAttribute(\"aria-live\", \"polite\");\n this.summaryElement.textContent = \"Loading PDF preview...\";\n\n const controls = document.createElement(\"div\");\n controls.className = \"controls\";\n this.zoomOutButton = createButton(\"-\", \"Zoom out\");\n this.scaleElement = document.createElement(\"output\");\n this.scaleElement.className = \"scale\";\n this.scaleElement.setAttribute(\"aria-label\", \"Preview zoom\");\n this.zoomInButton = createButton(\"+\", \"Zoom in\");\n const fitButton = createButton(\"Fit\", \"Fit pages to preview width\");\n controls.append(this.zoomOutButton, this.scaleElement, this.zoomInButton, fitButton);\n toolbar.append(this.summaryElement, controls);\n\n this.pagesElement = document.createElement(\"div\");\n this.pagesElement.className = \"pages\";\n this.pagesElement.tabIndex = 0;\n this.pagesElement.setAttribute(\"aria-label\", \"PDF pages\");\n viewer.append(toolbar, this.pagesElement);\n this.shadow.append(style, viewer);\n this.target.replaceChildren(this.element);\n\n this.zoomOutButton.addEventListener(\"click\", () => {\n void this.setScale(this.scale - this.zoomStep).catch((error: unknown) => this.showError(error));\n });\n this.zoomInButton.addEventListener(\"click\", () => {\n void this.setScale(this.scale + this.zoomStep).catch((error: unknown) => this.showError(error));\n });\n fitButton.addEventListener(\"click\", () => {\n void this.fitToWidth().catch((error: unknown) => this.showError(error));\n });\n }\n\n /** @internal */\n static async open(\n target: HTMLElement,\n bytes: Uint8Array,\n pageCount: number,\n options: PdfPreviewOptions = {},\n onDispose?: () => void,\n ): Promise<PdfPreview> {\n if (!(target instanceof HTMLElement)) throw new TypeError(\"PDF preview target must be an HTMLElement\");\n const preview = new PdfPreview(target, bytes.slice(), pageCount, options, onDispose);\n try {\n await preview.load(options.initialScale ?? \"fit-width\");\n return preview;\n } catch (error) {\n preview.releaseDocument();\n preview.showError(error);\n throw error;\n }\n }\n\n /** Current logical PDF.js scale after option clamping. */\n get currentScale(): number {\n return this.scale;\n }\n\n /** Sets a clamped scale and rerenders every page canvas. */\n async setScale(value: number): Promise<void> {\n this.assertActive();\n const next = clamp(value, this.minScale, this.maxScale);\n if (Math.abs(next - this.scale) < 0.001) return;\n this.scale = next;\n await this.renderPages();\n }\n\n /** Fits the first page to the available viewer width and rerenders all pages. */\n async fitToWidth(): Promise<void> {\n this.assertActive();\n const pdf = this.document;\n if (!pdf) return;\n const firstPage = await pdf.getPage(1);\n const viewport = firstPage.getViewport({ scale: 1 });\n firstPage.cleanup();\n const availableWidth = Math.max(this.pagesElement.clientWidth - 56, 120);\n this.scale = clamp(availableWidth / viewport.width, this.minScale, this.maxScale);\n await this.renderPages();\n }\n\n /** Cancels active work, destroys PDF.js state, and clears the target. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.renderVersion += 1;\n this.renderTask?.cancel();\n this.renderTask = undefined;\n this.releaseDocument();\n if (this.element.parentNode === this.target) this.target.replaceChildren();\n this.onDispose?.();\n }\n\n private async load(initialScale: number | \"fit-width\"): Promise<void> {\n const pdfJs = await loadPdfJs();\n this.assertActive();\n this.loadingTask = pdfJs.getDocument({ data: this.bytes });\n this.document = await this.loadingTask.promise;\n this.assertActive();\n if (this.document.numPages !== this.expectedPageCount) {\n throw new Error(`Preview loaded ${this.document.numPages} pages; renderer reported ${this.expectedPageCount}`);\n }\n if (initialScale === \"fit-width\") {\n const firstPage = await this.document.getPage(1);\n const viewport = firstPage.getViewport({ scale: 1 });\n firstPage.cleanup();\n const availableWidth = Math.max(this.pagesElement.clientWidth - 56, 120);\n this.scale = clamp(availableWidth / viewport.width, this.minScale, this.maxScale);\n } else {\n this.scale = clamp(initialScale, this.minScale, this.maxScale);\n }\n await this.renderPages();\n }\n\n /**\n * Renders pages serially so progress, cancellation, and memory use remain\n * deterministic across browsers.\n */\n private async renderPages(): Promise<void> {\n const pdf = this.document;\n if (!pdf) return;\n const version = ++this.renderVersion;\n this.renderTask?.cancel();\n this.renderTask = undefined;\n this.pagesElement.replaceChildren();\n this.updateControls();\n\n for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber += 1) {\n if (this.disposed || version !== this.renderVersion) return;\n this.summaryElement.textContent = `Rendering page ${pageNumber} of ${pdf.numPages}`;\n const page = await pdf.getPage(pageNumber);\n const viewport = page.getViewport({ scale: this.scale });\n const canvas = document.createElement(\"canvas\");\n canvas.width = Math.max(Math.floor(viewport.width * this.pixelRatio), 1);\n canvas.height = Math.max(Math.floor(viewport.height * this.pixelRatio), 1);\n canvas.style.width = `${Math.floor(viewport.width)}px`;\n canvas.style.height = `${Math.floor(viewport.height)}px`;\n canvas.setAttribute(\"role\", \"img\");\n canvas.setAttribute(\"aria-label\", `PDF page ${pageNumber} of ${pdf.numPages}`);\n\n const pageElement = document.createElement(\"article\");\n pageElement.className = \"page\";\n pageElement.dataset.pageNumber = String(pageNumber);\n pageElement.append(canvas);\n this.pagesElement.append(pageElement);\n\n const renderOptions: Parameters<PdfJsPage[\"render\"]>[0] = { canvas, viewport };\n if (this.pixelRatio !== 1) renderOptions.transform = [this.pixelRatio, 0, 0, this.pixelRatio, 0, 0];\n const renderTask = page.render(renderOptions);\n this.renderTask = renderTask;\n try {\n await renderTask.promise;\n } catch (error) {\n if (this.disposed || version !== this.renderVersion) return;\n throw error;\n } finally {\n if (this.renderTask === renderTask) this.renderTask = undefined;\n page.cleanup();\n }\n this.onProgress?.(pageNumber, pdf.numPages);\n }\n\n if (version === this.renderVersion) {\n this.summaryElement.textContent = `${pdf.numPages} ${pdf.numPages === 1 ? \"page\" : \"pages\"}`;\n this.updateControls();\n }\n }\n\n private updateControls(): void {\n this.scaleElement.value = `${Math.round(this.scale * 100)}%`;\n this.zoomOutButton.disabled = this.scale <= this.minScale + 0.001;\n this.zoomInButton.disabled = this.scale >= this.maxScale - 0.001;\n }\n\n private showError(error: unknown): void {\n if (this.disposed) return;\n this.pagesElement.replaceChildren();\n const message = document.createElement(\"p\");\n message.className = \"error\";\n message.setAttribute(\"role\", \"alert\");\n message.textContent = `PDF preview failed: ${error instanceof Error ? error.message : String(error)}`;\n this.pagesElement.append(message);\n this.summaryElement.textContent = \"Preview unavailable\";\n }\n\n private releaseDocument(): void {\n if (this.document) void this.document.destroy();\n else if (this.loadingTask) void this.loadingTask.destroy();\n this.document = undefined;\n this.loadingTask = undefined;\n }\n\n private assertActive(): void {\n if (this.disposed) throw new Error(\"PdfPreview has been disposed\");\n }\n}\n\nfunction createButton(label: string, ariaLabel: string): HTMLButtonElement {\n const button = document.createElement(\"button\");\n button.className = \"zoom\";\n button.type = \"button\";\n button.textContent = label;\n button.setAttribute(\"aria-label\", ariaLabel);\n return button;\n}\n\nfunction clamp(value: number, minimum: number, maximum: number): number {\n return Math.min(Math.max(value, minimum), maximum);\n}\n"]}
1
+ {"version":3,"file":"preview.js","sourceRoot":"","sources":["../src/preview.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAiEH,MAAM,aAAa,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6IrB,CAAC;AAEF,IAAI,WAA6C,CAAC;AAElD,sFAAsF;AACtF,KAAK,UAAU,SAAS;IACtB,WAAW,KAAK,MAAM,CAAC,kBAAkB,CAAC,IAAI,GAAG,CAAC,sBAAsB,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;SAC7F,IAAI,CAAC,CAAC,MAAe,EAAE,EAAE;QACxB,MAAM,KAAK,GAAG,MAAqB,CAAC;QACpC,KAAK,CAAC,mBAAmB,CAAC,SAAS,GAAG,IAAI,GAAG,CAAC,6BAA6B,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC;QACnG,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;SACD,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QACxB,WAAW,GAAG,SAAS,CAAC;QACxB,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;IACL,OAAO,WAAW,CAAC;AACrB,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,OAAO,UAAU;IAuBF,MAAM;IACN,KAAK;IACL,iBAAiB;IAEjB,SAAS;IA1B5B,qDAAqD;IAC5C,OAAO,CAAc;IAEb,MAAM,CAAa;IACnB,YAAY,CAAc;IAC1B,cAAc,CAAc;IAC5B,YAAY,CAAoB;IAChC,aAAa,CAAoB;IACjC,YAAY,CAAoB;IAChC,QAAQ,CAAS;IACjB,QAAQ,CAAS;IACjB,QAAQ,CAAS;IACjB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,IAAI,IAAI,CAAC,QAAQ;YAAE,KAAK,IAAI,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC;aAC3C,IAAI,IAAI,CAAC,WAAW;YAAE,KAAK,IAAI,CAAC,WAAW,CAAC,OAAO,EAAE,CAAC;QAC3D,IAAI,CAAC,QAAQ,GAAG,SAAS,CAAC;QAC1B,IAAI,CAAC,WAAW,GAAG,SAAS,CAAC;IAC/B,CAAC;IAEO,YAAY;QAClB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAC;IACrE,CAAC;CACF;AAED,SAAS,YAAY,CAAC,KAAa,EAAE,SAAiB;IACpD,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;IAChD,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC;IAC1B,MAAM,CAAC,IAAI,GAAG,QAAQ,CAAC;IACvB,MAAM,CAAC,WAAW,GAAG,KAAK,CAAC;IAC3B,MAAM,CAAC,YAAY,CAAC,YAAY,EAAE,SAAS,CAAC,CAAC;IAC7C,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,SAAS,KAAK,CAAC,KAAa,EAAE,OAAe,EAAE,OAAe;IAC5D,OAAO,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,OAAO,CAAC,CAAC;AACrD,CAAC","sourcesContent":["/**\n * Shadow-DOM PDF preview backed by package-relative PDF.js assets.\n *\n * @packageDocumentation\n */\n\n/** Color theme used by the integrated PDF preview controls. */\nexport type PdfPreviewTheme = \"system\" | \"light\" | \"dark\";\n\n/** Display and rendering limits for `PdfDocument.preview`. */\nexport interface PdfPreviewOptions {\n /** Whether to show the page summary and zoom toolbar. Defaults to `true`. */\n showToolbar?: boolean;\n /** Padding around the rendered pages in CSS pixels. Defaults to `28`, or `16` on narrow screens. */\n padding?: number;\n /** Initial zoom or automatic fit. Defaults to `fit-width`. */\n initialScale?: number | \"fit-width\";\n /** Lowest permitted zoom. Defaults to `0.25` and is never below `0.1`. */\n minScale?: number;\n /** Highest permitted zoom. Defaults to `3` and is never below `minScale`. */\n maxScale?: number;\n /** Zoom-button increment. Defaults to `0.25` and is never below `0.05`. */\n zoomStep?: number;\n /** Device-pixel-ratio cap used for page canvases. Defaults to `2`. */\n maxPixelRatio?: number;\n /** Accessible label for the preview region. Defaults to `PDF preview`. */\n ariaLabel?: string;\n /** Preview-control theme. Defaults to `system` and follows the browser preference. */\n theme?: PdfPreviewTheme;\n /** Called after each page canvas completes rendering. */\n onProgress?: (completedPages: number, totalPages: number) => void;\n}\n\ninterface PdfJsViewport {\n readonly width: number;\n readonly height: number;\n}\n\ninterface PdfJsRenderTask {\n readonly promise: Promise<void>;\n cancel(): void;\n}\n\ninterface PdfJsPage {\n getViewport(options: { scale: number }): PdfJsViewport;\n render(options: {\n canvas: HTMLCanvasElement;\n viewport: PdfJsViewport;\n transform?: readonly [number, number, number, number, number, number];\n }): PdfJsRenderTask;\n cleanup(): void;\n}\n\ninterface PdfJsDocument {\n readonly numPages: number;\n getPage(pageNumber: number): Promise<PdfJsPage>;\n destroy(): Promise<void>;\n}\n\ninterface PdfJsLoadingTask {\n readonly promise: Promise<PdfJsDocument>;\n destroy(): Promise<void>;\n}\n\ninterface PdfJsModule {\n readonly GlobalWorkerOptions: { workerSrc: string };\n getDocument(options: { data: Uint8Array }): PdfJsLoadingTask;\n}\n\nconst VIEWER_STYLES = `\n :host {\n --preview-scale: #33404d;\n --preview-summary: #52606d;\n --preview-focus: #111;\n --preview-toolbar: rgba(255, 255, 255, 0.96);\n --preview-toolbar-line: rgba(24, 32, 42, 0.10);\n --preview-zoom: #fff;\n --preview-zoom-hover: #f5f7fa;\n --preview-zoom-ink: #18202a;\n --preview-zoom-line: rgba(24, 32, 42, 0.16);\n color: #18202a;\n color-scheme: light dark;\n display: block;\n font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", sans-serif;\n -webkit-font-smoothing: antialiased;\n }\n *, *::before, *::after { box-sizing: border-box; }\n button { font: inherit; touch-action: manipulation; }\n .viewer {\n background: #e9edf2;\n border-radius: 14px;\n box-shadow: 0 0 0 1px rgba(24, 32, 42, 0.12), 0 18px 50px rgba(24, 32, 42, 0.10);\n display: grid;\n grid-template-rows: auto minmax(320px, 1fr);\n isolation: isolate;\n min-height: 520px;\n overflow: hidden;\n }\n .viewer.toolbar-hidden { grid-template-rows: minmax(320px, 1fr); }\n .toolbar {\n align-items: center;\n background: var(--preview-toolbar);\n box-shadow: 0 1px 0 var(--preview-toolbar-line);\n display: flex;\n gap: 8px;\n justify-content: space-between;\n min-height: 60px;\n padding: 8px 12px;\n }\n .toolbar[hidden] { display: none; }\n .summary {\n color: var(--preview-summary);\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n min-width: 9rem;\n }\n .controls { align-items: center; display: flex; gap: 6px; }\n .zoom {\n background: var(--preview-zoom);\n border: 0;\n border-radius: 9px;\n box-shadow: 0 0 0 1px var(--preview-zoom-line);\n color: var(--preview-zoom-ink);\n cursor: pointer;\n min-height: 44px;\n min-width: 44px;\n padding: 0 12px;\n }\n .zoom:focus-visible { outline: 2px solid var(--preview-focus); outline-offset: 2px; }\n .zoom:disabled { cursor: not-allowed; opacity: 0.42; }\n .scale {\n color: var(--preview-scale);\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n min-width: 3.75rem;\n text-align: center;\n }\n .pages {\n align-items: center;\n display: flex;\n flex-direction: column;\n gap: 24px;\n overflow: auto;\n overscroll-behavior: contain;\n padding: 28px;\n }\n .page {\n background: #fff;\n box-shadow: 0 0 0 1px rgba(24, 32, 42, 0.10), 0 10px 30px rgba(24, 32, 42, 0.14);\n flex: 0 0 auto;\n line-height: 0;\n }\n canvas { display: block; }\n .error {\n align-self: center;\n color: #9f1239;\n font-size: 14px;\n line-height: 1.5;\n margin: auto;\n max-width: 36rem;\n padding: 32px;\n text-align: center;\n }\n @media (hover: hover) and (pointer: fine) {\n .zoom:not(:disabled):hover { background: var(--preview-zoom-hover); }\n }\n @media (prefers-color-scheme: dark) {\n :host {\n --preview-scale: #d7dee7;\n --preview-summary: #b7c0ca;\n --preview-focus: #fff;\n --preview-toolbar: rgba(24, 32, 42, 0.96);\n --preview-toolbar-line: rgba(255, 255, 255, 0.12);\n --preview-zoom: #26313c;\n --preview-zoom-hover: #303c48;\n --preview-zoom-ink: #f8fafc;\n --preview-zoom-line: rgba(255, 255, 255, 0.18);\n }\n }\n :host([data-theme=\"light\"]) {\n --preview-scale: #33404d;\n --preview-summary: #52606d;\n --preview-focus: #111;\n --preview-toolbar: rgba(255, 255, 255, 0.96);\n --preview-toolbar-line: rgba(24, 32, 42, 0.10);\n --preview-zoom: #fff;\n --preview-zoom-hover: #f5f7fa;\n --preview-zoom-ink: #18202a;\n --preview-zoom-line: rgba(24, 32, 42, 0.16);\n color-scheme: light;\n }\n :host([data-theme=\"dark\"]) {\n --preview-scale: #d7dee7;\n --preview-summary: #b7c0ca;\n --preview-focus: #fff;\n --preview-toolbar: rgba(24, 32, 42, 0.96);\n --preview-toolbar-line: rgba(255, 255, 255, 0.12);\n --preview-zoom: #26313c;\n --preview-zoom-hover: #303c48;\n --preview-zoom-ink: #f8fafc;\n --preview-zoom-line: rgba(255, 255, 255, 0.18);\n color-scheme: dark;\n }\n @media (max-width: 560px) {\n .viewer { border-radius: 10px; min-height: 440px; }\n .toolbar { align-items: flex-start; flex-direction: column; }\n .controls { width: 100%; }\n .controls .zoom:last-child { margin-left: auto; }\n .pages { gap: 16px; padding: 16px; }\n }\n`;\n\nlet pdfJsModule: Promise<PdfJsModule> | undefined;\n\n/** Lazily loads one shared PDF.js module while keeping preview assets relocatable. */\nasync function loadPdfJs(): Promise<PdfJsModule> {\n pdfJsModule ??= import(/* @vite-ignore */ new URL(\"./vendor/pdf.min.mjs\", import.meta.url).href)\n .then((module: unknown) => {\n const pdfJs = module as PdfJsModule;\n pdfJs.GlobalWorkerOptions.workerSrc = new URL(\"./vendor/pdf.worker.min.mjs\", import.meta.url).href;\n return pdfJs;\n })\n .catch((error: unknown) => {\n pdfJsModule = undefined;\n throw error;\n });\n return pdfJsModule;\n}\n\n/**\n * Interactive canvas preview created and owned by a `PdfDocument`.\n *\n * @remarks\n * The viewer replaces the target's children with one isolated Shadow DOM\n * subtree. Dispose it to cancel rendering, destroy PDF.js state, and clear the\n * target. Construct previews through `PdfDocument.preview`.\n */\nexport class PdfPreview {\n /** Host element inserted into the preview target. */\n readonly element: HTMLElement;\n\n private readonly shadow: ShadowRoot;\n private readonly pagesElement: HTMLElement;\n private readonly summaryElement: HTMLElement;\n private readonly scaleElement: HTMLOutputElement;\n private readonly zoomOutButton: HTMLButtonElement;\n private readonly zoomInButton: HTMLButtonElement;\n private readonly minScale: number;\n private readonly maxScale: number;\n private readonly zoomStep: number;\n private readonly pixelRatio: number;\n private readonly onProgress: ((completedPages: number, totalPages: number) => void) | undefined;\n private loadingTask: PdfJsLoadingTask | undefined;\n private document: PdfJsDocument | undefined;\n private renderTask: PdfJsRenderTask | undefined;\n private scale = 1;\n private renderVersion = 0;\n private disposed = false;\n\n private constructor(\n private readonly target: HTMLElement,\n private readonly bytes: Uint8Array,\n private readonly expectedPageCount: number,\n options: PdfPreviewOptions,\n private readonly onDispose?: () => void,\n ) {\n this.minScale = Math.max(options.minScale ?? 0.25, 0.1);\n this.maxScale = Math.max(options.maxScale ?? 3, this.minScale);\n this.zoomStep = Math.max(options.zoomStep ?? 0.25, 0.05);\n this.pixelRatio = Math.min(Math.max(window.devicePixelRatio || 1, 1), options.maxPixelRatio ?? 2);\n this.onProgress = options.onProgress;\n\n this.element = document.createElement(\"div\");\n this.element.dataset.html2realpdfPreview = \"\";\n this.setTheme(options.theme ?? \"system\");\n this.shadow = this.element.attachShadow({ mode: \"open\" });\n\n const style = document.createElement(\"style\");\n style.textContent = VIEWER_STYLES;\n const viewer = document.createElement(\"section\");\n viewer.className = \"viewer\";\n viewer.setAttribute(\"role\", \"region\");\n viewer.setAttribute(\"aria-label\", options.ariaLabel ?? \"PDF preview\");\n\n const toolbar = document.createElement(\"div\");\n toolbar.className = \"toolbar\";\n toolbar.hidden = options.showToolbar === false;\n if (toolbar.hidden) viewer.classList.add(\"toolbar-hidden\");\n this.summaryElement = document.createElement(\"div\");\n this.summaryElement.className = \"summary\";\n this.summaryElement.setAttribute(\"aria-live\", \"polite\");\n this.summaryElement.textContent = \"Loading PDF preview...\";\n\n const controls = document.createElement(\"div\");\n controls.className = \"controls\";\n this.zoomOutButton = createButton(\"-\", \"Zoom out\");\n this.scaleElement = document.createElement(\"output\");\n this.scaleElement.className = \"scale\";\n this.scaleElement.setAttribute(\"aria-label\", \"Preview zoom\");\n this.zoomInButton = createButton(\"+\", \"Zoom in\");\n const fitButton = createButton(\"Fit\", \"Fit pages to preview width\");\n controls.append(this.zoomOutButton, this.scaleElement, this.zoomInButton, fitButton);\n toolbar.append(this.summaryElement, controls);\n\n this.pagesElement = document.createElement(\"div\");\n this.pagesElement.className = \"pages\";\n if (options.padding !== undefined && Number.isFinite(options.padding)) {\n this.pagesElement.style.padding = `${Math.max(options.padding, 0)}px`;\n }\n this.pagesElement.tabIndex = 0;\n this.pagesElement.setAttribute(\"aria-label\", \"PDF pages\");\n viewer.append(toolbar, this.pagesElement);\n this.shadow.append(style, viewer);\n this.target.replaceChildren(this.element);\n\n this.zoomOutButton.addEventListener(\"click\", () => {\n void this.setScale(this.scale - this.zoomStep).catch((error: unknown) => this.showError(error));\n });\n this.zoomInButton.addEventListener(\"click\", () => {\n void this.setScale(this.scale + this.zoomStep).catch((error: unknown) => this.showError(error));\n });\n fitButton.addEventListener(\"click\", () => {\n void this.fitToWidth().catch((error: unknown) => this.showError(error));\n });\n }\n\n /** @internal */\n static async open(\n target: HTMLElement,\n bytes: Uint8Array,\n pageCount: number,\n options: PdfPreviewOptions = {},\n onDispose?: () => void,\n ): Promise<PdfPreview> {\n if (!(target instanceof HTMLElement)) throw new TypeError(\"PDF preview target must be an HTMLElement\");\n const preview = new PdfPreview(target, bytes.slice(), pageCount, options, onDispose);\n try {\n await preview.load(options.initialScale ?? \"fit-width\");\n return preview;\n } catch (error) {\n preview.releaseDocument();\n preview.showError(error);\n throw error;\n }\n }\n\n /** Current logical PDF.js scale after option clamping. */\n get currentScale(): number {\n return this.scale;\n }\n\n /** Current preview-control theme, including the default `system` mode. */\n get currentTheme(): PdfPreviewTheme {\n return this.element.dataset.theme as PdfPreviewTheme;\n }\n\n /** Updates the preview-control theme without rerendering the PDF pages. */\n setTheme(theme: PdfPreviewTheme): void {\n this.assertActive();\n if (theme !== \"system\" && theme !== \"light\" && theme !== \"dark\") {\n throw new TypeError(`Unsupported PDF preview theme: ${String(theme)}`);\n }\n this.element.dataset.theme = theme;\n }\n\n /** Sets a clamped scale and rerenders every page canvas. */\n async setScale(value: number): Promise<void> {\n this.assertActive();\n const next = clamp(value, this.minScale, this.maxScale);\n if (Math.abs(next - this.scale) < 0.001) return;\n this.scale = next;\n await this.renderPages();\n }\n\n /** Fits the first page to the available viewer width and rerenders all pages. */\n async fitToWidth(): Promise<void> {\n this.assertActive();\n const pdf = this.document;\n if (!pdf) return;\n const firstPage = await pdf.getPage(1);\n const viewport = firstPage.getViewport({ scale: 1 });\n firstPage.cleanup();\n this.scale = clamp(this.availablePageWidth() / viewport.width, this.minScale, this.maxScale);\n await this.renderPages();\n }\n\n /** Cancels active work, destroys PDF.js state, and clears the target. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.renderVersion += 1;\n this.renderTask?.cancel();\n this.renderTask = undefined;\n this.releaseDocument();\n if (this.element.parentNode === this.target) this.target.replaceChildren();\n this.onDispose?.();\n }\n\n private async load(initialScale: number | \"fit-width\"): Promise<void> {\n const pdfJs = await loadPdfJs();\n this.assertActive();\n this.loadingTask = pdfJs.getDocument({ data: this.bytes });\n this.document = await this.loadingTask.promise;\n this.assertActive();\n if (this.document.numPages !== this.expectedPageCount) {\n throw new Error(`Preview loaded ${this.document.numPages} pages; renderer reported ${this.expectedPageCount}`);\n }\n if (initialScale === \"fit-width\") {\n const firstPage = await this.document.getPage(1);\n const viewport = firstPage.getViewport({ scale: 1 });\n firstPage.cleanup();\n this.scale = clamp(this.availablePageWidth() / viewport.width, this.minScale, this.maxScale);\n } else {\n this.scale = clamp(initialScale, this.minScale, this.maxScale);\n }\n await this.renderPages();\n }\n\n /**\n * Renders pages serially so progress, cancellation, and memory use remain\n * deterministic across browsers.\n */\n private async renderPages(): Promise<void> {\n const pdf = this.document;\n if (!pdf) return;\n const version = ++this.renderVersion;\n this.renderTask?.cancel();\n this.renderTask = undefined;\n this.pagesElement.replaceChildren();\n this.updateControls();\n\n for (let pageNumber = 1; pageNumber <= pdf.numPages; pageNumber += 1) {\n if (this.disposed || version !== this.renderVersion) return;\n this.summaryElement.textContent = `Rendering page ${pageNumber} of ${pdf.numPages}`;\n const page = await pdf.getPage(pageNumber);\n const viewport = page.getViewport({ scale: this.scale });\n const canvas = document.createElement(\"canvas\");\n canvas.width = Math.max(Math.floor(viewport.width * this.pixelRatio), 1);\n canvas.height = Math.max(Math.floor(viewport.height * this.pixelRatio), 1);\n canvas.style.width = `${Math.floor(viewport.width)}px`;\n canvas.style.height = `${Math.floor(viewport.height)}px`;\n canvas.setAttribute(\"role\", \"img\");\n canvas.setAttribute(\"aria-label\", `PDF page ${pageNumber} of ${pdf.numPages}`);\n\n const pageElement = document.createElement(\"article\");\n pageElement.className = \"page\";\n pageElement.dataset.pageNumber = String(pageNumber);\n pageElement.append(canvas);\n this.pagesElement.append(pageElement);\n\n const renderOptions: Parameters<PdfJsPage[\"render\"]>[0] = { canvas, viewport };\n if (this.pixelRatio !== 1) renderOptions.transform = [this.pixelRatio, 0, 0, this.pixelRatio, 0, 0];\n const renderTask = page.render(renderOptions);\n this.renderTask = renderTask;\n try {\n await renderTask.promise;\n } catch (error) {\n if (this.disposed || version !== this.renderVersion) return;\n throw error;\n } finally {\n if (this.renderTask === renderTask) this.renderTask = undefined;\n page.cleanup();\n }\n this.onProgress?.(pageNumber, pdf.numPages);\n }\n\n if (version === this.renderVersion) {\n this.summaryElement.textContent = `${pdf.numPages} ${pdf.numPages === 1 ? \"page\" : \"pages\"}`;\n this.updateControls();\n }\n }\n\n private updateControls(): void {\n this.scaleElement.value = `${Math.round(this.scale * 100)}%`;\n this.zoomOutButton.disabled = this.scale <= this.minScale + 0.001;\n this.zoomInButton.disabled = this.scale >= this.maxScale - 0.001;\n }\n\n private availablePageWidth(): number {\n const style = getComputedStyle(this.pagesElement);\n const horizontalPadding = Number.parseFloat(style.paddingLeft) + Number.parseFloat(style.paddingRight);\n return Math.max(this.pagesElement.clientWidth - horizontalPadding, 120);\n }\n\n private showError(error: unknown): void {\n if (this.disposed) return;\n this.pagesElement.replaceChildren();\n const message = document.createElement(\"p\");\n message.className = \"error\";\n message.setAttribute(\"role\", \"alert\");\n message.textContent = `PDF preview failed: ${error instanceof Error ? error.message : String(error)}`;\n this.pagesElement.append(message);\n this.summaryElement.textContent = \"Preview unavailable\";\n }\n\n private releaseDocument(): void {\n if (this.document) void this.document.destroy();\n else if (this.loadingTask) void this.loadingTask.destroy();\n this.document = undefined;\n this.loadingTask = undefined;\n }\n\n private assertActive(): void {\n if (this.disposed) throw new Error(\"PdfPreview has been disposed\");\n }\n}\n\nfunction createButton(label: string, ariaLabel: string): HTMLButtonElement {\n const button = document.createElement(\"button\");\n button.className = \"zoom\";\n button.type = \"button\";\n button.textContent = label;\n button.setAttribute(\"aria-label\", ariaLabel);\n return button;\n}\n\nfunction clamp(value: number, minimum: number, maximum: number): number {\n return Math.min(Math.max(value, minimum), maximum);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imggion/html2realpdf",
3
- "version": "0.1.0",
3
+ "version": "0.1.13",
4
4
  "description": "Browser-first HTML to real, selectable PDF rendering powered by Zig and WebAssembly",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -114,6 +114,8 @@ Pass these options to `PdfDocument.preview`:
114
114
 
115
115
  | Option | Values and default |
116
116
  | --- | --- |
117
+ | `showToolbar` | `true` by default; set to `false` to hide the summary and zoom controls |
118
+ | `padding` | Non-negative CSS pixel value; `28` by default and `16` on narrow screens |
117
119
  | `initialScale` | `"fit-width"` (default) or a numeric scale |
118
120
  | `minScale` | `0.25` by default, clamped to at least `0.1` |
119
121
  | `maxScale` | `3` by default, clamped to at least `minScale` |