@imggion/html2realpdf 0.3.1 → 0.4.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 CHANGED
@@ -6,9 +6,6 @@
6
6
  <a href="https://www.npmjs.com/package/@imggion/html2realpdf">
7
7
  <img src="https://img.shields.io/npm/v/@imggion/html2realpdf.svg?style=flat-square" alt="npm version">
8
8
  </a>
9
- <a href="https://github.com/imggion/html2realpdf/releases/tag/v0.3.1">
10
- <img src="https://img.shields.io/badge/release-0.3.1-2ea44f?style=flat-square" alt="Latest release: 0.3.1">
11
- </a>
12
9
  <a href="#compliance">
13
10
  <img src="https://img.shields.io/badge/PDF%2FA--3u-d32f2f?style=flat-square&amp;logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSJub25lIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTE0IDJINXYyMGgxNFY3ek0xNCAydjVoNSIvPjx0ZXh0IHg9IjEyIiB5PSIxNyIgZmlsbD0id2hpdGUiIGZvbnQtZmFtaWx5PSJBcmlhbCxzYW5zLXNlcmlmIiBmb250LXNpemU9IjciIGZvbnQtd2VpZ2h0PSJib2xkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QREY8L3RleHQ%2BPC9zdmc%2B" alt="PDF/A-3u">
14
11
  </a>
@@ -20,7 +17,7 @@
20
17
  <img src="https://img.shields.io/badge/-TypeScript-3178c6?style=flat-square&amp;logo=typescript&amp;logoColor=white" alt="TypeScript">
21
18
  </p>
22
19
  <p>
23
- Generate selectable, searchable, vector-based PDFs from HTML in the browser.<br>
20
+ Generate selectable, searchable, vector-based PDFs and JPEG images from HTML, in the browser or in Node.<br>
24
21
  Written in Zig, compiled to WebAssembly, and packaged with a typed TypeScript API.
25
22
  </p>
26
23
  </div>
@@ -34,6 +31,8 @@
34
31
  - [Vue](#vue)
35
32
  - [Preview](#preview)
36
33
  - [Page layouts](#page-layouts)
34
+ - [Images](#images)
35
+ - [Node and servers](#node-and-servers)
37
36
  - [PDF/A and attachments](#pdfa-and-attachments)
38
37
  - [Compliance](#compliance)
39
38
  - [Benchmark](#benchmark)
@@ -214,6 +213,102 @@ const pdf = await renderPdf(postcard, {
214
213
  });
215
214
  ```
216
215
 
216
+ ## Images
217
+
218
+ `renderImage()` takes the same sources and snapshot options as `renderPdf()`
219
+ (elements, refs, HTML strings, `resourceResolver`, `resourcePolicy`,
220
+ `mediaType`, `viewport`, `canvasToSvg`, ...) and returns a JPEG. The same
221
+ layout and display list feed a rasterizer and JPEG encoder written in Zig,
222
+ so text, borders, gradients, shadows, PNG images, canvases, and inline SVG
223
+ charts all become pixels without a browser screenshot API.
224
+
225
+ ```ts
226
+ import { renderImage } from "@imggion/html2realpdf";
227
+
228
+ const image = await renderImage(chartRef, {
229
+ width: 800, // CSS width; defaults to the element's rendered width
230
+ scale: 2, // device pixels per CSS pixel (0.5–4), default 1
231
+ quality: 0.8, // 0–1, default 0.8 = 80%, like canvas.toBlob
232
+ chromaSubsampling: "4:4:4", // default "4:2:0", or "4:4:4" when quality >= 0.9
233
+ background: "#ffffff",
234
+ });
235
+ image.width; image.height; // device pixels
236
+ image.download("chart.jpg");
237
+ image.dispose();
238
+ ```
239
+
240
+ The image height follows the content, so a whole report becomes one tall
241
+ image and page breaks are ignored. `quality` uses the libjpeg scale shared by
242
+ Photoshop, Lightroom, and `canvas.toBlob`. Values outside 0–1 (for example
243
+ `quality: 80`) throw a `RangeError` instead of being clamped; `0` encodes at
244
+ the minimum quality (1%) and adds an `IMAGE_QUALITY_ADJUSTED` diagnostic.
245
+ Output is limited to 16,777,216 pixels and a 4096 CSS pixel width. The
246
+ default `cssProfile` for images is `web`.
247
+
248
+ JPEG resources inside the page are converted to PNG during the browser
249
+ snapshot. Link annotations have no pixel representation and are omitted.
250
+ `createRenderer()` instances expose the same method as `renderer.renderImage()`.
251
+
252
+ ## Node and servers
253
+
254
+ In Node the same import renders HTML strings without a browser, for example
255
+ markup from React's `renderToStaticMarkup`:
256
+
257
+ ```ts
258
+ import { readFile, writeFile } from "node:fs/promises";
259
+ import { renderToStaticMarkup } from "react-dom/server";
260
+ import { createRenderer } from "@imggion/html2realpdf"; // or "@imggion/html2realpdf/node"
261
+
262
+ const renderer = await createRenderer({
263
+ fonts: [{ family: "Inter", data: await readFile("fonts/Inter-Regular.ttf") }],
264
+ });
265
+ try {
266
+ const html = renderToStaticMarkup(<ReportDocument data={data} />);
267
+ const image = await renderer.renderImage(html, { width: 1200, scale: 2, quality: 0.8 });
268
+ await writeFile("report.jpg", image.bytes);
269
+
270
+ const pdf = await renderer.render(html, { cssProfile: "web" });
271
+ await writeFile("report.pdf", pdf.toUint8Array());
272
+ } finally {
273
+ renderer.dispose();
274
+ }
275
+ ```
276
+
277
+ The package `exports` select this build under the `node` condition, so
278
+ browser bundles never include it. Differences from the browser:
279
+
280
+ - Sources must be HTML strings; Elements and refs throw
281
+ `UnsupportedEnvironmentError` because they need a DOM.
282
+ - The WASM module is read from the packaged file (override with `wasmPath`
283
+ or `wasmBytes`) and renders run on the calling thread.
284
+ - Nothing is fetched. `<img src>`, `<link rel="stylesheet">`, and CSS
285
+ `url(...)` references go through `resourceResolver`, which must return CSS
286
+ text for stylesheets and a PNG, JPEG, or SVG data URL or `Blob` for images.
287
+ Relative URLs need `baseUrl`. Without a resolver, or when it returns
288
+ `null`, `resourcePolicy` decides: `"error"` (default) throws
289
+ `ResourceLoadError`, `"omit"` removes the resource with a `RESOURCE_OMITTED`
290
+ diagnostic.
291
+ - Fonts other than the built-in Noto families must be registered with
292
+ `createRenderer({ fonts })`.
293
+ - Inline `<svg>` is drawn natively at its CSS or `width`/`height`/`viewBox`
294
+ size, with `currentColor`, presentation attributes, inline styles, and
295
+ stylesheet rules (classes, `var()`) applied to its elements. SVG outside the
296
+ native subset (`<foreignObject>`, filters, `<use>`, ...) cannot be
297
+ rasterized without a browser: it throws `UnsupportedCssError` with the
298
+ default `fallback: "error"`, and is left blank with an
299
+ `INLINE_SVG_UNSUPPORTED` diagnostic otherwise. Malformed SVG follows
300
+ `resourcePolicy` (`INLINE_SVG_INVALID`). SVG text never becomes page text.
301
+ - JPEG `<img>` sources are embedded in PDFs but not decoded by the image
302
+ rasterizer (`IMAGE_FORMAT_NOT_RASTERIZED`); use PNG for `renderImage`.
303
+ - Browser-only options (`viewport`, `mediaType`, `includeShadowDom`,
304
+ `canvasToSvg`, `enableLinks: false`) have no effect. `toBlob()` works,
305
+ `download()` and `preview()` need a browser.
306
+ - HTML strings are styled by the core cascade. It matches type, class, id,
307
+ universal, descendant, and child selectors; rules using pseudo-classes or
308
+ attribute selectors are skipped, and pseudo-element selectors are dropped
309
+ from their selector list. `line-height` does not inherit yet and `normal`
310
+ is 1.2em, so set it on the elements where it matters.
311
+
217
312
  ## PDF/A and attachments
218
313
 
219
314
  Opt into PDF/A-3u independently of the CSS profile:
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Raster image option normalization and the owned `RenderedImage` result.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ import type { ChromaSubsampling, Diagnostic, ImageFormat, ImageRenderOptions } from "./types.js";
7
+ /** Default `quality`, matching the common `canvas.toBlob(cb, "image/jpeg", 0.8)` choice. */
8
+ export declare const DEFAULT_IMAGE_QUALITY = 0.8;
9
+ /** Default canvas width in CSS pixels for HTML strings without a viewport. */
10
+ export declare const DEFAULT_IMAGE_WIDTH = 800;
11
+ /** Image options in the units of the WASM JSON contract. */
12
+ export interface NormalizedImageOptions {
13
+ format: ImageFormat;
14
+ widthCss: number;
15
+ scale: number;
16
+ /** Integer encoder quality from 1 to 100. */
17
+ quality: number;
18
+ chromaSubsampling: ChromaSubsampling;
19
+ background: string;
20
+ }
21
+ /**
22
+ * Validates public image options and converts `quality` from 0...1 to the
23
+ * encoder's 1...100 integer.
24
+ *
25
+ * @remarks
26
+ * Out-of-range values throw instead of clamping, so `quality: 80` written as a
27
+ * percentage fails loudly rather than encoding at maximum quality. Only `0`
28
+ * and tiny positive values are raised to the minimum valid JPEG quality, and
29
+ * that adjustment is reported as a diagnostic.
30
+ *
31
+ * @throws {RangeError} for invalid format, quality, scale, width, or subsampling.
32
+ */
33
+ export declare function normalizeImageOptions(options: ImageRenderOptions, defaultWidth: number): {
34
+ options: NormalizedImageOptions;
35
+ diagnostics: Diagnostic[];
36
+ };
37
+ /**
38
+ * Encoded image returned by `renderImage`.
39
+ *
40
+ * @remarks
41
+ * Byte exports are defensive copies. `dispose` revokes object URLs created
42
+ * through this instance and invalidates later exports. Instances are
43
+ * renderer-owned results and cannot be constructed directly.
44
+ */
45
+ export declare class RenderedImage {
46
+ private readonly data;
47
+ /** Width in device pixels (CSS width multiplied by `scale`). */
48
+ readonly width: number;
49
+ /** Height in device pixels, derived from the laid-out content. */
50
+ readonly height: number;
51
+ /** Diagnostics retained from option normalization, snapshotting, and native rendering. */
52
+ readonly diagnostics: readonly Diagnostic[];
53
+ /** Encoded format. */
54
+ readonly format: ImageFormat;
55
+ /** MIME type of `bytes`. */
56
+ readonly mimeType = "image/jpeg";
57
+ private readonly objectUrls;
58
+ private disposed;
59
+ private constructor();
60
+ /** A defensive copy of the encoded bytes. */
61
+ get bytes(): Uint8Array;
62
+ /** Returns a defensive copy of the encoded bytes. */
63
+ toUint8Array(): Uint8Array;
64
+ /** Returns a standalone copy suitable for storage or transfer APIs. */
65
+ toArrayBuffer(): ArrayBuffer;
66
+ /** Returns a new Blob typed with `mimeType`. */
67
+ toBlob(): Blob;
68
+ /** Returns a `data:` URL, convenient for small images and `<img src>`. */
69
+ toDataURL(): string;
70
+ /**
71
+ * Creates an object URL tracked by this image.
72
+ *
73
+ * @remarks Revoke long-lived URLs explicitly or let `dispose` revoke them.
74
+ */
75
+ createObjectURL(): string;
76
+ /** Revokes an object URL previously created by this image. */
77
+ revokeObjectURL(url: string): void;
78
+ /** Starts a browser download and revokes its temporary object URL. */
79
+ download(filename?: string): void;
80
+ /** Revokes object URLs and invalidates byte exports. */
81
+ dispose(): void;
82
+ private assertActive;
83
+ }
package/dist/image.js ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Raster image option normalization and the owned `RenderedImage` result.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ /** Default `quality`, matching the common `canvas.toBlob(cb, "image/jpeg", 0.8)` choice. */
7
+ export const DEFAULT_IMAGE_QUALITY = 0.8;
8
+ /** Default canvas width in CSS pixels for HTML strings without a viewport. */
9
+ export const DEFAULT_IMAGE_WIDTH = 800;
10
+ const MIN_SCALE = 0.5;
11
+ const MAX_SCALE = 4;
12
+ const MAX_WIDTH = 4096;
13
+ /**
14
+ * Validates public image options and converts `quality` from 0...1 to the
15
+ * encoder's 1...100 integer.
16
+ *
17
+ * @remarks
18
+ * Out-of-range values throw instead of clamping, so `quality: 80` written as a
19
+ * percentage fails loudly rather than encoding at maximum quality. Only `0`
20
+ * and tiny positive values are raised to the minimum valid JPEG quality, and
21
+ * that adjustment is reported as a diagnostic.
22
+ *
23
+ * @throws {RangeError} for invalid format, quality, scale, width, or subsampling.
24
+ */
25
+ export function normalizeImageOptions(options, defaultWidth) {
26
+ const diagnostics = [];
27
+ const format = options.format ?? "jpeg";
28
+ if (format !== "jpeg")
29
+ throw new RangeError(`Unsupported image format ${JSON.stringify(format)}; only "jpeg" is available`);
30
+ const rawQuality = options.quality ?? DEFAULT_IMAGE_QUALITY;
31
+ if (typeof rawQuality !== "number" || Number.isNaN(rawQuality) || rawQuality < 0 || rawQuality > 1) {
32
+ throw new RangeError(`Image quality must be a number from 0 to 1 (0.8 means 80%); received ${String(rawQuality)}`);
33
+ }
34
+ const percent = Math.round(rawQuality * 100);
35
+ const quality = Math.min(Math.max(percent, 1), 100);
36
+ if (quality !== percent) {
37
+ diagnostics.push({
38
+ code: "IMAGE_QUALITY_ADJUSTED",
39
+ severity: "warning",
40
+ message: `JPEG quality ${rawQuality} is below the minimum encoder quality; encoded at 0.01 (1%)`,
41
+ phase: "raster",
42
+ });
43
+ }
44
+ const scale = options.scale ?? 1;
45
+ if (typeof scale !== "number" || !Number.isFinite(scale) || scale < MIN_SCALE || scale > MAX_SCALE) {
46
+ throw new RangeError(`Image scale must be between ${MIN_SCALE} and ${MAX_SCALE}; received ${String(scale)}`);
47
+ }
48
+ const widthCss = options.width ?? defaultWidth;
49
+ if (typeof widthCss !== "number" || !Number.isFinite(widthCss) || widthCss < 1 || widthCss > MAX_WIDTH) {
50
+ throw new RangeError(`Image width must be between 1 and ${MAX_WIDTH} CSS pixels; received ${String(widthCss)}`);
51
+ }
52
+ const chromaSubsampling = options.chromaSubsampling ?? (quality >= 90 ? "4:4:4" : "4:2:0");
53
+ if (chromaSubsampling !== "4:2:0" && chromaSubsampling !== "4:4:4") {
54
+ throw new RangeError(`chromaSubsampling must be "4:2:0" or "4:4:4"; received ${String(chromaSubsampling)}`);
55
+ }
56
+ return {
57
+ options: {
58
+ format,
59
+ widthCss,
60
+ scale,
61
+ quality,
62
+ chromaSubsampling,
63
+ background: options.background ?? "#ffffff",
64
+ },
65
+ diagnostics,
66
+ };
67
+ }
68
+ /**
69
+ * Encoded image returned by `renderImage`.
70
+ *
71
+ * @remarks
72
+ * Byte exports are defensive copies. `dispose` revokes object URLs created
73
+ * through this instance and invalidates later exports. Instances are
74
+ * renderer-owned results and cannot be constructed directly.
75
+ */
76
+ export class RenderedImage {
77
+ data;
78
+ width;
79
+ height;
80
+ /** Diagnostics retained from option normalization, snapshotting, and native rendering. */
81
+ diagnostics;
82
+ /** Encoded format. */
83
+ format = "jpeg";
84
+ /** MIME type of `bytes`. */
85
+ mimeType = "image/jpeg";
86
+ objectUrls = new Set();
87
+ disposed = false;
88
+ constructor(data,
89
+ /** Width in device pixels (CSS width multiplied by `scale`). */
90
+ width,
91
+ /** Height in device pixels, derived from the laid-out content. */
92
+ height, diagnostics) {
93
+ this.data = data;
94
+ this.width = width;
95
+ this.height = height;
96
+ this.diagnostics = Object.freeze([...diagnostics]);
97
+ }
98
+ /** @internal */
99
+ static create(data, width, height, diagnostics = []) {
100
+ return new RenderedImage(data, width, height, diagnostics);
101
+ }
102
+ /** A defensive copy of the encoded bytes. */
103
+ get bytes() {
104
+ return this.toUint8Array();
105
+ }
106
+ /** Returns a defensive copy of the encoded bytes. */
107
+ toUint8Array() {
108
+ this.assertActive();
109
+ return this.data.slice();
110
+ }
111
+ /** Returns a standalone copy suitable for storage or transfer APIs. */
112
+ toArrayBuffer() {
113
+ return this.toUint8Array().buffer;
114
+ }
115
+ /** Returns a new Blob typed with `mimeType`. */
116
+ toBlob() {
117
+ return new Blob([this.toArrayBuffer()], { type: this.mimeType });
118
+ }
119
+ /** Returns a `data:` URL, convenient for small images and `<img src>`. */
120
+ toDataURL() {
121
+ const bytes = this.toUint8Array();
122
+ let binary = "";
123
+ for (let offset = 0; offset < bytes.length; offset += 16_384) {
124
+ binary += String.fromCharCode(...bytes.subarray(offset, Math.min(offset + 16_384, bytes.length)));
125
+ }
126
+ return `data:${this.mimeType};base64,${btoa(binary)}`;
127
+ }
128
+ /**
129
+ * Creates an object URL tracked by this image.
130
+ *
131
+ * @remarks Revoke long-lived URLs explicitly or let `dispose` revoke them.
132
+ */
133
+ createObjectURL() {
134
+ const url = URL.createObjectURL(this.toBlob());
135
+ this.objectUrls.add(url);
136
+ return url;
137
+ }
138
+ /** Revokes an object URL previously created by this image. */
139
+ revokeObjectURL(url) {
140
+ if (!this.objectUrls.delete(url))
141
+ return;
142
+ URL.revokeObjectURL(url);
143
+ }
144
+ /** Starts a browser download and revokes its temporary object URL. */
145
+ download(filename = "image.jpg") {
146
+ const url = this.createObjectURL();
147
+ const anchor = document.createElement("a");
148
+ anchor.href = url;
149
+ anchor.download = filename;
150
+ document.body.append(anchor);
151
+ anchor.click();
152
+ anchor.remove();
153
+ queueMicrotask(() => this.revokeObjectURL(url));
154
+ }
155
+ /** Revokes object URLs and invalidates byte exports. */
156
+ dispose() {
157
+ if (this.disposed)
158
+ return;
159
+ for (const url of this.objectUrls)
160
+ URL.revokeObjectURL(url);
161
+ this.objectUrls.clear();
162
+ this.disposed = true;
163
+ }
164
+ assertActive() {
165
+ if (this.disposed)
166
+ throw new Error("RenderedImage has been disposed");
167
+ }
168
+ }
169
+ //# sourceMappingURL=image.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image.js","sourceRoot":"","sources":["../src/image.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,4FAA4F;AAC5F,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AACzC,8EAA8E;AAC9E,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AACvC,MAAM,SAAS,GAAG,GAAG,CAAC;AACtB,MAAM,SAAS,GAAG,CAAC,CAAC;AACpB,MAAM,SAAS,GAAG,IAAI,CAAC;AAavB;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,qBAAqB,CACnC,OAA2B,EAC3B,YAAoB;IAEpB,MAAM,WAAW,GAAiB,EAAE,CAAC;IACrC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,MAAM,CAAC;IACxC,IAAI,MAAM,KAAK,MAAM;QAAE,MAAM,IAAI,UAAU,CAAC,4BAA4B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,4BAA4B,CAAC,CAAC;IAE5H,MAAM,UAAU,GAAG,OAAO,CAAC,OAAO,IAAI,qBAAqB,CAAC;IAC5D,IAAI,OAAO,UAAU,KAAK,QAAQ,IAAI,MAAM,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,CAAC,IAAI,UAAU,GAAG,CAAC,EAAE,CAAC;QACnG,MAAM,IAAI,UAAU,CAAC,wEAAwE,MAAM,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;IAC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I,CAAC,eAAe,EAAE,CAAC;QACnC,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC;QAC3C,MAAM,CAAC,IAAI,GAAG,GAAG,CAAC;QAClB,MAAM,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAC3B,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAC7B,MAAM,CAAC,KAAK,EAAE,CAAC;QACf,MAAM,CAAC,MAAM,EAAE,CAAC;QAChB,cAAc,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,CAAC;IAClD,CAAC;IAED,wDAAwD;IACxD,OAAO;QACL,IAAI,IAAI,CAAC,QAAQ;YAAE,OAAO;QAC1B,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU;YAAE,GAAG,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;QAC5D,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;IACvB,CAAC;IAEO,YAAY;QAClB,IAAI,IAAI,CAAC,QAAQ;YAAE,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;IACxE,CAAC;CACF","sourcesContent":["/**\n * Raster image option normalization and the owned `RenderedImage` result.\n *\n * @packageDocumentation\n */\n\nimport type { ChromaSubsampling, Diagnostic, ImageFormat, ImageRenderOptions } from \"./types.js\";\n\n/** Default `quality`, matching the common `canvas.toBlob(cb, \"image/jpeg\", 0.8)` choice. */\nexport const DEFAULT_IMAGE_QUALITY = 0.8;\n/** Default canvas width in CSS pixels for HTML strings without a viewport. */\nexport const DEFAULT_IMAGE_WIDTH = 800;\nconst MIN_SCALE = 0.5;\nconst MAX_SCALE = 4;\nconst MAX_WIDTH = 4096;\n\n/** Image options in the units of the WASM JSON contract. */\nexport interface NormalizedImageOptions {\n format: ImageFormat;\n widthCss: number;\n scale: number;\n /** Integer encoder quality from 1 to 100. */\n quality: number;\n chromaSubsampling: ChromaSubsampling;\n background: string;\n}\n\n/**\n * Validates public image options and converts `quality` from 0...1 to the\n * encoder's 1...100 integer.\n *\n * @remarks\n * Out-of-range values throw instead of clamping, so `quality: 80` written as a\n * percentage fails loudly rather than encoding at maximum quality. Only `0`\n * and tiny positive values are raised to the minimum valid JPEG quality, and\n * that adjustment is reported as a diagnostic.\n *\n * @throws {RangeError} for invalid format, quality, scale, width, or subsampling.\n */\nexport function normalizeImageOptions(\n options: ImageRenderOptions,\n defaultWidth: number,\n): { options: NormalizedImageOptions; diagnostics: Diagnostic[] } {\n const diagnostics: Diagnostic[] = [];\n const format = options.format ?? \"jpeg\";\n if (format !== \"jpeg\") throw new RangeError(`Unsupported image format ${JSON.stringify(format)}; only \"jpeg\" is available`);\n\n const rawQuality = options.quality ?? DEFAULT_IMAGE_QUALITY;\n if (typeof rawQuality !== \"number\" || Number.isNaN(rawQuality) || rawQuality < 0 || rawQuality > 1) {\n throw new RangeError(`Image quality must be a number from 0 to 1 (0.8 means 80%); received ${String(rawQuality)}`);\n }\n const percent = Math.round(rawQuality * 100);\n const quality = Math.min(Math.max(percent, 1), 100);\n if (quality !== percent) {\n diagnostics.push({\n code: \"IMAGE_QUALITY_ADJUSTED\",\n severity: \"warning\",\n message: `JPEG quality ${rawQuality} is below the minimum encoder quality; encoded at 0.01 (1%)`,\n phase: \"raster\",\n });\n }\n\n const scale = options.scale ?? 1;\n if (typeof scale !== \"number\" || !Number.isFinite(scale) || scale < MIN_SCALE || scale > MAX_SCALE) {\n throw new RangeError(`Image scale must be between ${MIN_SCALE} and ${MAX_SCALE}; received ${String(scale)}`);\n }\n\n const widthCss = options.width ?? defaultWidth;\n if (typeof widthCss !== \"number\" || !Number.isFinite(widthCss) || widthCss < 1 || widthCss > MAX_WIDTH) {\n throw new RangeError(`Image width must be between 1 and ${MAX_WIDTH} CSS pixels; received ${String(widthCss)}`);\n }\n\n const chromaSubsampling = options.chromaSubsampling ?? (quality >= 90 ? \"4:4:4\" : \"4:2:0\");\n if (chromaSubsampling !== \"4:2:0\" && chromaSubsampling !== \"4:4:4\") {\n throw new RangeError(`chromaSubsampling must be \"4:2:0\" or \"4:4:4\"; received ${String(chromaSubsampling)}`);\n }\n\n return {\n options: {\n format,\n widthCss,\n scale,\n quality,\n chromaSubsampling,\n background: options.background ?? \"#ffffff\",\n },\n diagnostics,\n };\n}\n\n/**\n * Encoded image returned by `renderImage`.\n *\n * @remarks\n * Byte exports are defensive copies. `dispose` revokes object URLs created\n * through this instance and invalidates later exports. Instances are\n * renderer-owned results and cannot be constructed directly.\n */\nexport class RenderedImage {\n /** Diagnostics retained from option normalization, snapshotting, and native rendering. */\n readonly diagnostics: readonly Diagnostic[];\n /** Encoded format. */\n readonly format: ImageFormat = \"jpeg\";\n /** MIME type of `bytes`. */\n readonly mimeType = \"image/jpeg\";\n private readonly objectUrls = new Set<string>();\n private disposed = false;\n\n private constructor(\n private readonly data: Uint8Array,\n /** Width in device pixels (CSS width multiplied by `scale`). */\n readonly width: number,\n /** Height in device pixels, derived from the laid-out content. */\n readonly height: number,\n diagnostics: readonly Diagnostic[],\n ) {\n this.diagnostics = Object.freeze([...diagnostics]);\n }\n\n /** @internal */\n static create(data: Uint8Array, width: number, height: number, diagnostics: readonly Diagnostic[] = []): RenderedImage {\n return new RenderedImage(data, width, height, diagnostics);\n }\n\n /** A defensive copy of the encoded bytes. */\n get bytes(): Uint8Array {\n return this.toUint8Array();\n }\n\n /** Returns a defensive copy of the encoded bytes. */\n toUint8Array(): Uint8Array {\n this.assertActive();\n return this.data.slice();\n }\n\n /** Returns a standalone copy suitable for storage or transfer APIs. */\n toArrayBuffer(): ArrayBuffer {\n return this.toUint8Array().buffer as ArrayBuffer;\n }\n\n /** Returns a new Blob typed with `mimeType`. */\n toBlob(): Blob {\n return new Blob([this.toArrayBuffer()], { type: this.mimeType });\n }\n\n /** Returns a `data:` URL, convenient for small images and `<img src>`. */\n toDataURL(): string {\n const bytes = this.toUint8Array();\n let binary = \"\";\n for (let offset = 0; offset < bytes.length; offset += 16_384) {\n binary += String.fromCharCode(...bytes.subarray(offset, Math.min(offset + 16_384, bytes.length)));\n }\n return `data:${this.mimeType};base64,${btoa(binary)}`;\n }\n\n /**\n * Creates an object URL tracked by this image.\n *\n * @remarks Revoke long-lived URLs explicitly or let `dispose` revoke them.\n */\n createObjectURL(): string {\n const url = URL.createObjectURL(this.toBlob());\n this.objectUrls.add(url);\n return url;\n }\n\n /** Revokes an object URL previously created by this image. */\n revokeObjectURL(url: string): void {\n if (!this.objectUrls.delete(url)) return;\n URL.revokeObjectURL(url);\n }\n\n /** Starts a browser download and revokes its temporary object URL. */\n download(filename = \"image.jpg\"): void {\n const url = this.createObjectURL();\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = filename;\n document.body.append(anchor);\n anchor.click();\n anchor.remove();\n queueMicrotask(() => this.revokeObjectURL(url));\n }\n\n /** Revokes object URLs and invalidates byte exports. */\n dispose(): void {\n if (this.disposed) return;\n for (const url of this.objectUrls) URL.revokeObjectURL(url);\n this.objectUrls.clear();\n this.disposed = true;\n }\n\n private assertActive(): void {\n if (this.disposed) throw new Error(\"RenderedImage has been disposed\");\n }\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Browser-first HTML-to-PDF rendering with selectable text, native vectors,
3
- * typed configuration, and an html2pdf.js compatibility layer.
2
+ * Browser-first HTML-to-PDF and HTML-to-image rendering with selectable text,
3
+ * native vectors, typed configuration, and an html2pdf.js compatibility layer.
4
4
  *
5
5
  * @packageDocumentation
6
6
  */
@@ -10,5 +10,6 @@ export { CompatWorker } from "./compat.js";
10
10
  export * from "./errors.js";
11
11
  export { PdfDocument } from "./pdf-document.js";
12
12
  export { PdfPreview, type PdfPreviewOptions, type PdfPreviewTheme } from "./preview.js";
13
- export { createRenderer, Html2RealPdf, renderPdf } from "./renderer.js";
13
+ export { RenderedImage } from "./image.js";
14
+ export { createRenderer, Html2RealPdf, renderImage, renderPdf } from "./renderer.js";
14
15
  export type * from "./types.js";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Browser-first HTML-to-PDF rendering with selectable text, native vectors,
3
- * typed configuration, and an html2pdf.js compatibility layer.
2
+ * Browser-first HTML-to-PDF and HTML-to-image rendering with selectable text,
3
+ * native vectors, typed configuration, and an html2pdf.js compatibility layer.
4
4
  *
5
5
  * @packageDocumentation
6
6
  */
@@ -10,5 +10,6 @@ export { CompatWorker } from "./compat.js";
10
10
  export * from "./errors.js";
11
11
  export { PdfDocument } from "./pdf-document.js";
12
12
  export { PdfPreview } from "./preview.js";
13
- export { createRenderer, Html2RealPdf, renderPdf } from "./renderer.js";
13
+ export { RenderedImage } from "./image.js";
14
+ export { createRenderer, Html2RealPdf, renderImage, renderPdf } from "./renderer.js";
14
15
  //# sourceMappingURL=index.js.map
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,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"]}
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,aAAa,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC","sourcesContent":["/**\n * Browser-first HTML-to-PDF and HTML-to-image rendering with selectable text,\n * native vectors, 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 { RenderedImage } from \"./image.js\";\nexport { createRenderer, Html2RealPdf, renderImage, renderPdf } from \"./renderer.js\";\nexport type * from \"./types.js\";\n"]}
Binary file
@@ -0,0 +1,16 @@
1
+ /**
2
+ * HTML-string preparation for hosts without a DOM (Node).
3
+ *
4
+ * The browser snapshot embeds every resource and replaces inline SVG before
5
+ * the core runs. Without a DOM the core does the structural work itself
6
+ * (inline `<svg>` becomes a replaced element natively); this module only
7
+ * routes external resources through `resourceResolver`, using byte ranges the
8
+ * core tokenizer reports, and maps core diagnostics onto the caller's
9
+ * policies after the render. Nothing is ever fetched implicitly.
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ import type { SourcePreparation } from "./renderer.js";
14
+ import type { WasmBridge } from "./wasm.js";
15
+ /** Source preparation for one Node renderer and its WASM bridge. */
16
+ export declare function nodeSourcePreparation(bridge: WasmBridge): SourcePreparation;
@@ -0,0 +1,155 @@
1
+ /**
2
+ * HTML-string preparation for hosts without a DOM (Node).
3
+ *
4
+ * The browser snapshot embeds every resource and replaces inline SVG before
5
+ * the core runs. Without a DOM the core does the structural work itself
6
+ * (inline `<svg>` becomes a replaced element natively); this module only
7
+ * routes external resources through `resourceResolver`, using byte ranges the
8
+ * core tokenizer reports, and maps core diagnostics onto the caller's
9
+ * policies after the render. Nothing is ever fetched implicitly.
10
+ *
11
+ * @packageDocumentation
12
+ */
13
+ import { ResourceLoadError, UnsupportedCssError, UnsupportedEnvironmentError } from "./errors.js";
14
+ const EMBEDDED_IMAGE = /^data:image\/(?:png|jpeg|jpg|svg\+xml);base64,/i;
15
+ const SVG_DATA_URL = /^data:image\/svg\+xml(?:;charset=[^;,]+)?,/i;
16
+ const EMBEDDABLE_BLOB_TYPES = new Set(["image/png", "image/jpeg", "image/svg+xml"]);
17
+ /** Source preparation for one Node renderer and its WASM bridge. */
18
+ export function nodeSourcePreparation(bridge) {
19
+ return {
20
+ prepare: (source, options) => prepareHtmlString(bridge, source, options),
21
+ check: enforceNodePolicies,
22
+ };
23
+ }
24
+ async function prepareHtmlString(bridge, source, options) {
25
+ if (typeof source !== "string") {
26
+ throw new UnsupportedEnvironmentError("Element and ref sources need a browser DOM; pass an HTML string when rendering in Node");
27
+ }
28
+ const diagnostics = [];
29
+ const references = bridge.resourceReferences(source);
30
+ if (references.length === 0)
31
+ return { html: source, diagnostics };
32
+ const edits = [];
33
+ for (const reference of references) {
34
+ let replacement;
35
+ try {
36
+ replacement = await resolveReference(reference, options);
37
+ }
38
+ catch (error) {
39
+ if (options.resourcePolicy === "error")
40
+ throw new ResourceLoadError(reference.url, { cause: error });
41
+ // Backgrounds stay in place: the core omits non-embedded URLs and
42
+ // reports them itself. Elements are removed like the browser snapshot.
43
+ if (reference.kind === "background" || reference.tagStart === undefined || reference.tagEnd === undefined)
44
+ continue;
45
+ addEdit(edits, { start: reference.tagStart, end: reference.tagEnd, text: "" });
46
+ diagnostics.push({
47
+ code: "RESOURCE_OMITTED",
48
+ severity: "warning",
49
+ message: `${reference.kind === "stylesheet" ? "Stylesheet" : "Image"} resource was omitted: ${reference.url}`,
50
+ phase: "snapshot",
51
+ });
52
+ continue;
53
+ }
54
+ if (reference.kind === "stylesheet" && reference.tagStart !== undefined && reference.tagEnd !== undefined) {
55
+ addEdit(edits, { start: reference.tagStart, end: reference.tagEnd, text: replacement });
56
+ }
57
+ else {
58
+ addEdit(edits, { start: reference.start, end: reference.end, text: replacement });
59
+ }
60
+ }
61
+ return { html: applyEdits(source, edits), diagnostics };
62
+ }
63
+ /** Returns the embedded replacement text, or throws when the resource is unavailable. */
64
+ async function resolveReference(reference, options) {
65
+ let url;
66
+ try {
67
+ url = options.baseUrl === undefined ? new URL(reference.url) : new URL(reference.url, options.baseUrl);
68
+ }
69
+ catch (error) {
70
+ throw new Error(`Relative resource URL "${reference.url}" needs baseUrl outside the browser`, { cause: error });
71
+ }
72
+ const resolver = options.resourceResolver;
73
+ if (!resolver)
74
+ throw new Error("Resources are never fetched outside the browser; provide resourceResolver");
75
+ const kind = reference.kind === "stylesheet" ? "stylesheet" : "image";
76
+ const resolved = await resolver({ kind, url });
77
+ if (resolved === null || resolved === undefined)
78
+ throw new Error(`The ${kind} resource was declined by resourceResolver`);
79
+ if (kind === "stylesheet") {
80
+ const css = typeof resolved === "string" ? resolved : await resolved.text();
81
+ // Raw-text content cannot contain its own end tag.
82
+ return `<style data-html2realpdf-resolved-from="${escapeAttribute(url.href)}">${css.replace(/<\/style/gi, "<\\/style")}</style>`;
83
+ }
84
+ if (typeof resolved === "string") {
85
+ if (EMBEDDED_IMAGE.test(resolved))
86
+ return resolved;
87
+ if (SVG_DATA_URL.test(resolved)) {
88
+ const payload = decodeURIComponent(resolved.slice(resolved.indexOf(",") + 1));
89
+ return `data:image/svg+xml;base64,${base64(new TextEncoder().encode(payload))}`;
90
+ }
91
+ throw new Error("Outside the browser an image resolver must return a PNG, JPEG, or SVG data URL or Blob; replacement URLs are not fetched");
92
+ }
93
+ const type = resolved.type.toLowerCase();
94
+ if (!EMBEDDABLE_BLOB_TYPES.has(type)) {
95
+ throw new Error(`Image type "${resolved.type || "unknown"}" cannot be embedded outside the browser; use PNG, JPEG, or SVG`);
96
+ }
97
+ return `data:${type};base64,${base64(new Uint8Array(await resolved.arrayBuffer()))}`;
98
+ }
99
+ /**
100
+ * Maps core diagnostics onto the browser-equivalent policies. The browser
101
+ * rasterizes unsupported SVG only after `fallback: "rasterize-subtree"`;
102
+ * Node cannot rasterize, so it keeps the omission and its diagnostic.
103
+ */
104
+ function enforceNodePolicies(diagnostics, options) {
105
+ const has = (code) => diagnostics.some((diagnostic) => diagnostic.code === code);
106
+ if (options.fallback === "error" && has("INLINE_SVG_UNSUPPORTED")) {
107
+ throw new UnsupportedCssError("Inline SVG uses features outside the native vector subset and cannot be rasterized outside the browser");
108
+ }
109
+ if (options.unsupportedCss === "error" && has("UNSUPPORTED_CSS_PROPERTY")) {
110
+ const property = diagnostics.find((diagnostic) => diagnostic.code === "UNSUPPORTED_CSS_PROPERTY")?.property ?? "unknown";
111
+ throw new UnsupportedCssError(`Unsupported CSS property: ${property}`);
112
+ }
113
+ if (options.resourcePolicy === "error") {
114
+ const failed = diagnostics.find((diagnostic) => diagnostic.code === "INLINE_SVG_INVALID" || diagnostic.code === "RESOURCE_OMITTED");
115
+ if (failed)
116
+ throw new ResourceLoadError(failed.code === "INLINE_SVG_INVALID" ? "inline SVG" : failed.message);
117
+ }
118
+ }
119
+ /** Keeps edits disjoint: an element removal supersedes edits inside it. */
120
+ function addEdit(edits, edit) {
121
+ if (edits.some((existing) => edit.start >= existing.start && edit.end <= existing.end && existing.end - existing.start > edit.end - edit.start))
122
+ return;
123
+ for (let index = edits.length - 1; index >= 0; index -= 1) {
124
+ const existing = edits[index];
125
+ if (existing.start >= edit.start && existing.end <= edit.end)
126
+ edits.splice(index, 1);
127
+ }
128
+ edits.push(edit);
129
+ }
130
+ /** Applies byte-range edits to the UTF-8 encoding of `source`. */
131
+ function applyEdits(source, edits) {
132
+ if (edits.length === 0)
133
+ return source;
134
+ const encoder = new TextEncoder();
135
+ const bytes = encoder.encode(source);
136
+ const decoder = new TextDecoder();
137
+ let output = "";
138
+ let cursor = 0;
139
+ for (const edit of [...edits].sort((left, right) => left.start - right.start)) {
140
+ output += decoder.decode(bytes.subarray(cursor, edit.start)) + edit.text;
141
+ cursor = edit.end;
142
+ }
143
+ return output + decoder.decode(bytes.subarray(cursor));
144
+ }
145
+ function escapeAttribute(value) {
146
+ return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;");
147
+ }
148
+ function base64(bytes) {
149
+ let binary = "";
150
+ for (let offset = 0; offset < bytes.length; offset += 0x8000) {
151
+ binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
152
+ }
153
+ return btoa(binary);
154
+ }
155
+ //# sourceMappingURL=node-source.js.map