@imggion/html2realpdf 0.1.0

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 ADDED
@@ -0,0 +1,292 @@
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.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @imggion/html2realpdf
11
+ ```
12
+
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`.
16
+
17
+ ## Choose an API
18
+
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 |
24
+
25
+ Use the modern API for new integrations. The compatibility API deliberately
26
+ rejects stages that depend on html2canvas or rasterized PDF pages.
27
+
28
+ ## Sources
29
+
30
+ `renderPdf` and `renderer.render` accept:
31
+
32
+ ```ts
33
+ type HtmlSource = string | Element | { readonly current: Element | null };
34
+ ```
35
+
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.
41
+
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`.
44
+
45
+ ## Render once
46
+
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 {
62
+ pdf.dispose();
63
+ }
64
+ ```
65
+
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.
69
+
70
+ ## Reuse a renderer
71
+
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
+ });
84
+
85
+ try {
86
+ const pdf = await renderer.render(
87
+ '<p style="font-family: Inter">Selectable text</p>',
88
+ );
89
+ try {
90
+ const blob = pdf.toBlob();
91
+ // Store or upload the Blob.
92
+ } finally {
93
+ pdf.dispose();
94
+ }
95
+ } finally {
96
+ renderer.dispose();
97
+ }
98
+ ```
99
+
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`. |
151
+
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
+ });
159
+ ```
160
+
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.
165
+
166
+ Scoped rasterization records `CSS_SUBTREE_RASTERIZED` or
167
+ `CANVAS_SUBTREE_RASTERIZED`. Inspect diagnostics before describing output as
168
+ fully vector.
169
+
170
+ ### Pagination, metadata, cancellation, and progress
171
+
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.
176
+
177
+ `metadata` accepts `title`, `author`, `subject`, `keywords`, and `creator`.
178
+ `keywords` may be a string or an array.
179
+
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.
183
+
184
+ ## PDF output and preview
185
+
186
+ `PdfDocument` exposes immutable output through:
187
+
188
+ - `toUint8Array()`, `toArrayBuffer()`, and `toBlob()`;
189
+ - `download(filename)`;
190
+ - `createObjectURL()` and `revokeObjectURL(url)`;
191
+ - `preview(target, options)`;
192
+ - `pageCount` and `diagnostics`.
193
+
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.
197
+
198
+ ```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),
206
+ });
207
+
208
+ await preview.setScale(1.25);
209
+ await preview.fitToWidth();
210
+ preview.dispose();
211
+ ```
212
+
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.
215
+
216
+ ## Diagnostics and errors
217
+
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.
222
+
223
+ The package exports these error classes:
224
+
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`.
233
+
234
+ Cancellation normally rejects with `AbortError`. Invalid page margins produce a
235
+ `RangeError`; lifecycle misuse after disposal produces a regular `Error`.
236
+
237
+ ## html2pdf.js compatibility
238
+
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();
251
+ ```
252
+
253
+ | Compatibility surface | Status |
254
+ | --- | --- |
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
273
+
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:
283
+
284
+ ```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
290
+ ```
291
+
292
+ The packaged model instructions live at `skills/html2realpdf/SKILL.md`.