@imggion/html2realpdf 0.1.0 → 0.1.1

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.
Files changed (2) hide show
  1. package/README.md +169 -228
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,292 +1,233 @@
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://github.com/imggion/html2realpdf/releases/tag/v0.1.1"><img src="https://img.shields.io/badge/release-0.1.1-2ea44f?style=flat-square" alt="Latest release: 0.1.1"></a>
7
+ <img src="https://img.shields.io/badge/-zig-f39b34?style=flat-square&amp;logo=zig&amp;logoColor=white" alt="Zig">
8
+ <img src="https://img.shields.io/badge/-WASM-654ff0?style=flat-square&amp;logo=webassembly&amp;logoColor=white" alt="WebAssembly">
9
+ <img src="https://img.shields.io/badge/-TypeScript-3178c6?style=flat-square&amp;logo=typescript&amp;logoColor=white" alt="TypeScript">
10
+ </p>
11
+ <p>
12
+ Generate selectable, searchable, vector-based PDFs from HTML in the browser.<br>
13
+ Written in Zig, compiled to WebAssembly, and packaged with a typed TypeScript API.
14
+ </p>
15
+ </div>
16
+
17
+ ## Contents
18
+
19
+ - [Why real PDFs](#why-real-pdfs)
20
+ - [Install](#install)
21
+ - [Quick start](#quick-start)
22
+ - [React](#react)
23
+ - [Vue](#vue)
24
+ - [Preview](#preview)
25
+ - [Page layouts](#page-layouts)
26
+ - [Benchmark](#benchmark)
27
+ - [Contributing](#contributing)
28
+ - [License](#license)
29
+
30
+ ## Why real PDFs
31
+
32
+ Screenshot-based PDF tools turn a page into an image. `html2realpdf` keeps text
33
+ as text, links as PDF annotations, fonts as embedded subsets, and supported
34
+ graphics as vectors.
35
+
36
+ The text includes Unicode mappings, so people can select, copy, and search the
37
+ result. Tools and LLMs can read the document text without first running OCR.
38
+ Text-heavy documents are also often smaller and stay sharp at every zoom level.
39
+
40
+ Zig performs the layout and PDF writing, while WebAssembly brings the renderer
41
+ to the browser. The result is one portable pipeline for invoices, reports,
42
+ tickets, letters, slides, and other web-generated documents.
43
+
44
+ See the [CSS support matrix](docs/css-support.md) for the current layout and
45
+ rendering coverage. The current release provides machine-readable text and accessible
46
+ preview controls; it does not claim PDF/UA or fully tagged PDF compliance.
6
47
 
7
48
  ## Install
8
49
 
50
+ Install the stable release with your package manager:
51
+
9
52
  ```sh
10
53
  npm install @imggion/html2realpdf
54
+ pnpm add @imggion/html2realpdf
55
+ yarn add @imggion/html2realpdf
56
+ bun add @imggion/html2realpdf
11
57
  ```
12
58
 
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`.
59
+ ## Quick start
16
60
 
17
- ## Choose an API
61
+ Render an HTML element, download the PDF, then release its resources:
18
62
 
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 |
63
+ ```ts
64
+ import { renderPdf } from "@imggion/html2realpdf";
24
65
 
25
- Use the modern API for new integrations. The compatibility API deliberately
26
- rejects stages that depend on html2canvas or rasterized PDF pages.
66
+ const invoice = document.querySelector<HTMLElement>("#invoice");
67
+ if (!invoice) throw new Error("Invoice not found");
27
68
 
28
- ## Sources
69
+ const pdf = await renderPdf(invoice);
70
+ pdf.download("invoice.pdf");
71
+ pdf.dispose();
72
+ ```
29
73
 
30
- `renderPdf` and `renderer.render` accept:
74
+ HTML strings are supported too:
31
75
 
32
76
  ```ts
33
- type HtmlSource = string | Element | { readonly current: Element | null };
77
+ const pdf = await renderPdf("<h1>Hello from a real PDF</h1>");
34
78
  ```
35
79
 
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.
80
+ ## React
41
81
 
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`.
82
+ Pass a ref to a mounted element. The package understands React-shaped refs
83
+ without depending on React itself.
44
84
 
45
- ## Render once
85
+ ```tsx
86
+ const reportRef = useRef<HTMLDivElement>(null);
46
87
 
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 {
88
+ async function downloadReport() {
89
+ if (!reportRef.current) return;
90
+
91
+ const pdf = await renderPdf(reportRef);
92
+ pdf.download("report.pdf");
62
93
  pdf.dispose();
63
94
  }
95
+
96
+ return <Report ref={reportRef} />;
64
97
  ```
65
98
 
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.
99
+ `Report` can be a component that forwards its ref to its root element. Pass the
100
+ mounted ref, not an unmounted component definition.
69
101
 
70
- ## Reuse a renderer
102
+ ## Vue
71
103
 
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
- });
104
+ Pass the mounted DOM element behind a template ref. With Vue 3.5 or newer,
105
+ `useTemplateRef()` keeps the element typed without wrapping the renderer in a
106
+ Vue-specific adapter.
84
107
 
85
- try {
86
- const pdf = await renderer.render(
87
- '<p style="font-family: Inter">Selectable text</p>',
88
- );
108
+ ```vue
109
+ <script setup lang="ts">
110
+ import { useTemplateRef } from "vue";
111
+ import { renderPdf } from "@imggion/html2realpdf";
112
+
113
+ const report = useTemplateRef<HTMLElement>("report");
114
+
115
+ async function downloadReport() {
116
+ if (!report.value) return;
117
+
118
+ const pdf = await renderPdf(report.value);
89
119
  try {
90
- const blob = pdf.toBlob();
91
- // Store or upload the Blob.
120
+ pdf.download("report.pdf");
92
121
  } finally {
93
122
  pdf.dispose();
94
123
  }
95
- } finally {
96
- renderer.dispose();
97
124
  }
98
- ```
125
+ </script>
99
126
 
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`. |
127
+ <template>
128
+ <article ref="report">
129
+ <h1>Quarterly report</h1>
130
+ <p>This content stays selectable in the PDF.</p>
131
+ </article>
151
132
 
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
- });
133
+ <button type="button" @click="downloadReport">Download PDF</button>
134
+ </template>
159
135
  ```
160
136
 
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.
137
+ On Vue 3.4 or earlier, use
138
+ `const report = ref<HTMLElement | null>(null)` with the same template ref and
139
+ pass `report.value` to `renderPdf()`.
165
140
 
166
- Scoped rasterization records `CSS_SUBTREE_RASTERIZED` or
167
- `CANVAS_SUBTREE_RASTERIZED`. Inspect diagnostics before describing output as
168
- fully vector.
141
+ ## Preview
169
142
 
170
- ### Pagination, metadata, cancellation, and progress
143
+ The preview renders the actual generated PDF inside your page. It uses isolated
144
+ Shadow DOM and canvas pages instead of an iframe, browser PDF plugin, or fake
145
+ HTML copy.
171
146
 
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.
147
+ ```ts
148
+ const pdf = await renderPdf(invoice);
149
+ const previewTarget = document.querySelector<HTMLElement>("#pdf-preview");
150
+ if (!previewTarget) throw new Error("Preview target not found");
176
151
 
177
- `metadata` accepts `title`, `author`, `subject`, `keywords`, and `creator`.
178
- `keywords` may be a string or an array.
152
+ const preview = await pdf.preview(previewTarget, {
153
+ initialScale: "fit-width",
154
+ });
179
155
 
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.
156
+ // Later, when closing the preview:
157
+ preview.dispose();
158
+ pdf.dispose();
159
+ ```
183
160
 
184
- ## PDF output and preview
161
+ ## Page layouts
185
162
 
186
- `PdfDocument` exposes immutable output through:
163
+ Use the named `a4` and `letter` formats in portrait or landscape mode. A4
164
+ landscape works well for presentation decks:
187
165
 
188
- - `toUint8Array()`, `toArrayBuffer()`, and `toBlob()`;
189
- - `download(filename)`;
190
- - `createObjectURL()` and `revokeObjectURL(url)`;
191
- - `preview(target, options)`;
192
- - `pageCount` and `diagnostics`.
166
+ ```ts
167
+ const pdf = await renderPdf(slides, {
168
+ page: {
169
+ format: "a4",
170
+ orientation: "landscape",
171
+ unit: "mm",
172
+ margin: [12, 12],
173
+ },
174
+ });
175
+ ```
193
176
 
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.
177
+ For postcards or any other size, pass custom `[width, height]` dimensions:
197
178
 
198
179
  ```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),
180
+ const pdf = await renderPdf(postcard, {
181
+ page: { format: [148, 105], unit: "mm", margin: 8 },
206
182
  });
207
-
208
- await preview.setScale(1.25);
209
- await preview.fitToWidth();
210
- preview.dispose();
211
183
  ```
212
184
 
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.
185
+ ## Benchmark
215
186
 
216
- ## Diagnostics and errors
187
+ One recorded run of the deterministic 30-page stress report produced:
217
188
 
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.
189
+ | Engine | First PDF | Warm render | File size | Pages | Content model |
190
+ | --- | ---: | ---: | ---: | ---: | --- |
191
+ | `html2realpdf` | 1595.9 ms | 1451.2 ms | 441.1 kB | 30 | Native/selectable PDF |
192
+ | `html2pdf.js` | 2124.6 ms | 1952.4 ms | 3.11 MB | 30 | Raster image PDF |
222
193
 
223
- The package exports these error classes:
194
+ **Main differences versus html2pdf.js**
224
195
 
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`.
196
+ - **33.1% faster first PDF**
197
+ - **34.5% faster warm render**
198
+ - **85.8% smaller file**
199
+ - and, of course, a REAL PDF 😏
233
200
 
234
- Cancellation normally rejects with `AbortError`. Invalid page margins produce a
235
- `RangeError`; lifecycle misuse after disposal produces a regular `Error`.
201
+ ## Contributing
236
202
 
237
- ## html2pdf.js compatibility
203
+ You need Zig `0.16.0`, Node.js `20.16+`, npm, and Make. On a fresh checkout,
204
+ install the JavaScript dependencies once:
238
205
 
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();
206
+ ```sh
207
+ npm ci --prefix bindings/js
208
+ npm ci --prefix tests/react
209
+ npm ci --prefix tests/web
251
210
  ```
252
211
 
253
- | Compatibility surface | Status |
212
+ | Command | Purpose |
254
213
  | --- | --- |
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
214
+ | `make test` | Run the Zig and renderer tests |
215
+ | `make release` | Build the native release binary |
216
+ | `make wasm` | Build the default `ReleaseFast` WebAssembly and browser package |
217
+ | `make wasm-small` | Build the optional size-oriented `ReleaseSmall` package asset |
218
+ | `make react` | Start the React integration app |
219
+ | `make test-release` | Run the complete release gate |
273
220
 
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:
221
+ To open the small browser test harness:
283
222
 
284
223
  ```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
224
+ make wasm
225
+ python3 -m http.server 8765
290
226
  ```
291
227
 
292
- The packaged model instructions live at `skills/html2realpdf/SKILL.md`.
228
+ Visit [http://localhost:8765/tests/web/index.html](http://localhost:8765/tests/web/index.html).
229
+
230
+ ## License
231
+
232
+ The project code is released under the MIT License. See [LICENSE.md](LICENSE.md)
233
+ for the complete project and third-party license inventory.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imggion/html2realpdf",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
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",