@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/dist/wasm.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Typed ownership bridge for the renderer's handle-based WebAssembly ABI.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ import type { NormalizedPage } from "./page.js";
7
+ import type { CssProfile, Diagnostic, FontRegistration, PdfMetadata } from "./types.js";
8
+ import type { SnapshotPageMarginBox, SnapshotPageRule } from "./snapshot.js";
9
+ /** Owned JavaScript result copied out of WASM memory. */
10
+ export interface WasmRenderResult {
11
+ bytes: Uint8Array;
12
+ pageCount: number;
13
+ diagnostics: Diagnostic[];
14
+ }
15
+ /**
16
+ * Owns one native PDF context and its registered fonts.
17
+ *
18
+ * @remarks
19
+ * All temporary allocations and result handles are freed before `render`
20
+ * returns. PDF bytes are copied first because freeing handles or growing WASM
21
+ * memory invalidates borrowed views.
22
+ */
23
+ export declare class WasmBridge {
24
+ private readonly exports;
25
+ private readonly context;
26
+ private readonly encoder;
27
+ private disposed;
28
+ private constructor();
29
+ /** Instantiates the expected ABI, creates a context, and registers its fonts. */
30
+ static create(wasmUrl: string | URL, fonts?: readonly FontRegistration[]): Promise<WasmBridge>;
31
+ /** Serializes render options, invokes the native renderer, and returns owned output. */
32
+ render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[]): WasmRenderResult;
33
+ /** Frees the renderer context and every font copied into it. */
34
+ dispose(): void;
35
+ /** Copies one font registration across the ABI into context-owned storage. */
36
+ private registerFont;
37
+ private readResultString;
38
+ private readDiagnostics;
39
+ }
package/dist/wasm.js ADDED
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Typed ownership bridge for the renderer's handle-based WebAssembly ABI.
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ import { WasmRenderError } from "./errors.js";
7
+ const EXPECTED_ABI_VERSION = 1;
8
+ /**
9
+ * Owns one native PDF context and its registered fonts.
10
+ *
11
+ * @remarks
12
+ * All temporary allocations and result handles are freed before `render`
13
+ * returns. PDF bytes are copied first because freeing handles or growing WASM
14
+ * memory invalidates borrowed views.
15
+ */
16
+ export class WasmBridge {
17
+ exports;
18
+ context;
19
+ encoder = new TextEncoder();
20
+ disposed = false;
21
+ constructor(exports, context) {
22
+ this.exports = exports;
23
+ this.context = context;
24
+ }
25
+ /** Instantiates the expected ABI, creates a context, and registers its fonts. */
26
+ static async create(wasmUrl, fonts = []) {
27
+ const response = await fetch(wasmUrl);
28
+ if (!response.ok)
29
+ throw new WasmRenderError(`Could not load WASM: HTTP ${response.status}`, -10);
30
+ let result;
31
+ try {
32
+ result = await WebAssembly.instantiateStreaming(response.clone(), {});
33
+ }
34
+ catch {
35
+ result = await WebAssembly.instantiate(await response.arrayBuffer(), {});
36
+ }
37
+ const exports = result.instance.exports;
38
+ const abiVersion = exports.html2realpdf_abi_version?.();
39
+ if (abiVersion !== EXPECTED_ABI_VERSION) {
40
+ throw new WasmRenderError(`Unsupported WASM ABI version ${String(abiVersion)}; expected ${EXPECTED_ABI_VERSION}`, -14);
41
+ }
42
+ const context = exports.pdf_context_create();
43
+ if (context === 0)
44
+ throw new WasmRenderError("WASM context allocation failed", -12);
45
+ const bridge = new WasmBridge(exports, context);
46
+ try {
47
+ for (const registration of fonts)
48
+ bridge.registerFont(registration);
49
+ return bridge;
50
+ }
51
+ catch (error) {
52
+ bridge.dispose();
53
+ throw error;
54
+ }
55
+ }
56
+ /** Serializes render options, invokes the native renderer, and returns owned output. */
57
+ render(html, page, metadata, cssProfile = "document", marginBoxes, pageRules) {
58
+ if (this.disposed)
59
+ throw new WasmRenderError("WASM bridge has been disposed", -15);
60
+ const input = this.encoder.encode(html);
61
+ const renderOptions = this.encoder.encode(JSON.stringify({
62
+ pageWidthPoints: page.widthPoints,
63
+ pageHeightPoints: page.heightPoints,
64
+ marginTopPoints: page.marginTopPoints,
65
+ marginRightPoints: page.marginRightPoints,
66
+ marginBottomPoints: page.marginBottomPoints,
67
+ marginLeftPoints: page.marginLeftPoints,
68
+ cssProfile,
69
+ marginBoxes,
70
+ pageRules,
71
+ metadata: metadata ? {
72
+ ...metadata,
73
+ keywords: Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords,
74
+ } : undefined,
75
+ }));
76
+ const inputPointer = this.exports.alloc(input.length);
77
+ if (inputPointer === 0)
78
+ throw new WasmRenderError("WASM input allocation failed", -11);
79
+ const optionsPointer = this.exports.alloc(renderOptions.length);
80
+ if (optionsPointer === 0) {
81
+ this.exports.free(inputPointer, input.length);
82
+ throw new WasmRenderError("WASM options allocation failed", -11);
83
+ }
84
+ let resultHandle = 0;
85
+ try {
86
+ new Uint8Array(this.exports.memory.buffer, inputPointer, input.length).set(input);
87
+ new Uint8Array(this.exports.memory.buffer, optionsPointer, renderOptions.length).set(renderOptions);
88
+ resultHandle = this.exports.render_html_to_pdf_with_context_json_options(this.context, inputPointer, input.length, optionsPointer, renderOptions.length);
89
+ if (resultHandle === 0)
90
+ throw new WasmRenderError("WASM result allocation failed", -12);
91
+ const status = this.exports.pdf_result_status(resultHandle);
92
+ if (status !== 0) {
93
+ const detail = this.readResultString(resultHandle, "error");
94
+ throw new WasmRenderError(detail || `WASM PDF rendering failed with status ${status}`, status);
95
+ }
96
+ const pointer = this.exports.pdf_result_data_ptr(resultHandle);
97
+ const length = this.exports.pdf_result_data_len(resultHandle);
98
+ if (pointer === 0 || length === 0)
99
+ throw new WasmRenderError("WASM returned an empty PDF", -13);
100
+ return {
101
+ bytes: new Uint8Array(this.exports.memory.buffer, pointer, length).slice(),
102
+ pageCount: this.exports.pdf_result_page_count(resultHandle),
103
+ diagnostics: this.readDiagnostics(resultHandle),
104
+ };
105
+ }
106
+ finally {
107
+ if (resultHandle !== 0)
108
+ this.exports.pdf_result_free(resultHandle);
109
+ this.exports.free(inputPointer, input.length);
110
+ this.exports.free(optionsPointer, renderOptions.length);
111
+ }
112
+ }
113
+ /** Frees the renderer context and every font copied into it. */
114
+ dispose() {
115
+ if (this.disposed)
116
+ return;
117
+ this.disposed = true;
118
+ this.exports.pdf_context_free(this.context);
119
+ }
120
+ /** Copies one font registration across the ABI into context-owned storage. */
121
+ registerFont(registration) {
122
+ const family = this.encoder.encode(registration.family.trim());
123
+ const data = registration.data instanceof Uint8Array
124
+ ? registration.data
125
+ : new Uint8Array(registration.data);
126
+ if (family.length === 0 || data.length === 0)
127
+ throw new WasmRenderError("Font family and data must not be empty", -16);
128
+ const familyPointer = this.exports.alloc(family.length);
129
+ const dataPointer = this.exports.alloc(data.length);
130
+ if (familyPointer === 0 || dataPointer === 0) {
131
+ if (familyPointer !== 0)
132
+ this.exports.free(familyPointer, family.length);
133
+ if (dataPointer !== 0)
134
+ this.exports.free(dataPointer, data.length);
135
+ throw new WasmRenderError("WASM font allocation failed", -11);
136
+ }
137
+ try {
138
+ new Uint8Array(this.exports.memory.buffer, familyPointer, family.length).set(family);
139
+ new Uint8Array(this.exports.memory.buffer, dataPointer, data.length).set(data);
140
+ const numericWeight = registration.weight === "bold" ? 700 : registration.weight === "normal" || registration.weight === undefined
141
+ ? 400
142
+ : registration.weight;
143
+ const status = this.exports.pdf_context_register_font(this.context, familyPointer, family.length, dataPointer, data.length, numericWeight, registration.style === "italic" ? 1 : 0);
144
+ if (status !== 0)
145
+ throw new WasmRenderError(`WASM font registration failed with status ${status}`, status);
146
+ }
147
+ finally {
148
+ this.exports.free(familyPointer, family.length);
149
+ this.exports.free(dataPointer, data.length);
150
+ }
151
+ }
152
+ readResultString(handle, kind) {
153
+ const pointer = kind === "error"
154
+ ? this.exports.pdf_result_error_ptr(handle)
155
+ : this.exports.pdf_result_diagnostics_ptr(handle);
156
+ const length = kind === "error"
157
+ ? this.exports.pdf_result_error_len(handle)
158
+ : this.exports.pdf_result_diagnostics_len(handle);
159
+ if (pointer === 0 || length === 0)
160
+ return "";
161
+ return new TextDecoder().decode(new Uint8Array(this.exports.memory.buffer, pointer, length));
162
+ }
163
+ readDiagnostics(handle) {
164
+ const serialized = this.readResultString(handle, "diagnostics");
165
+ if (!serialized)
166
+ return [];
167
+ try {
168
+ const parsed = JSON.parse(serialized);
169
+ return Array.isArray(parsed) ? parsed : [];
170
+ }
171
+ catch {
172
+ return [{ code: "INVALID_WASM_DIAGNOSTICS", severity: "warning", message: "WASM returned malformed diagnostics" }];
173
+ }
174
+ }
175
+ }
176
+ //# sourceMappingURL=wasm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wasm.js","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAK9C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAuD/B;;;;;;;GAOG;AACH,MAAM,OAAO,UAAU;IAIgB,OAAO;IAAgC,OAAO;IAHlE,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IACrC,QAAQ,GAAG,KAAK,CAAC;IAEzB,YAAqC,OAAoB,EAAmB,OAAe;uBAAtD,OAAO;uBAAgC,OAAO;IAAW,CAAC;IAE/F,iFAAiF;IACjF,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAqB,EAAE,KAAK,GAAgC,EAAE;QAChF,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;QACtC,IAAI,CAAC,QAAQ,CAAC,EAAE;YAAE,MAAM,IAAI,eAAe,CAAC,6BAA6B,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC;QAEjG,IAAI,MAAiD,CAAC;QACtD,IAAI,CAAC;YACH,MAAM,GAAG,MAAM,WAAW,CAAC,oBAAoB,CAAC,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,CAAC,CAAC;QACxE,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,GAAG,MAAM,WAAW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C7D,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,CAAC,EAAE,IAAI,EAAE,0BAA0B,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,qCAAqC,EAAE,CAAC,CAAC;QACrH,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * Typed ownership bridge for the renderer's handle-based WebAssembly ABI.\n *\n * @packageDocumentation\n */\n\nimport { WasmRenderError } from \"./errors.js\";\nimport type { NormalizedPage } from \"./page.js\";\nimport type { CssProfile, Diagnostic, FontRegistration, PdfMetadata } from \"./types.js\";\nimport type { SnapshotPageMarginBox, SnapshotPageRule } from \"./snapshot.js\";\n\nconst EXPECTED_ABI_VERSION = 1;\n\n/** ABI surface implemented by `src/wasm.zig`. */\ninterface WasmExports {\n html2realpdf_abi_version(): number;\n pdf_context_create(): number;\n pdf_context_free(handle: number): void;\n pdf_context_register_font(\n handle: number,\n familyPointer: number,\n familyLength: number,\n dataPointer: number,\n dataLength: number,\n weight: number,\n style: number,\n ): number;\n memory: WebAssembly.Memory;\n alloc(length: number): number;\n free(pointer: number, length: number): void;\n render_html_to_pdf_with_options(\n pointer: number,\n length: number,\n pageWidthPoints: number,\n pageHeightPoints: number,\n marginTopPoints: number,\n marginRightPoints: number,\n marginBottomPoints: number,\n marginLeftPoints: number,\n ): number;\n render_html_to_pdf_with_json_options(pointer: number, length: number, optionsPointer: number, optionsLength: number): number;\n render_html_to_pdf_with_context_json_options(\n context: number,\n pointer: number,\n length: number,\n optionsPointer: number,\n optionsLength: number,\n ): number;\n pdf_result_status(handle: number): number;\n pdf_result_data_ptr(handle: number): number;\n pdf_result_data_len(handle: number): number;\n pdf_result_page_count(handle: number): number;\n pdf_result_error_ptr(handle: number): number;\n pdf_result_error_len(handle: number): number;\n pdf_result_diagnostics_ptr(handle: number): number;\n pdf_result_diagnostics_len(handle: number): number;\n pdf_result_free(handle: number): void;\n}\n\n/** Owned JavaScript result copied out of WASM memory. */\nexport interface WasmRenderResult {\n bytes: Uint8Array;\n pageCount: number;\n diagnostics: Diagnostic[];\n}\n\n/**\n * Owns one native PDF context and its registered fonts.\n *\n * @remarks\n * All temporary allocations and result handles are freed before `render`\n * returns. PDF bytes are copied first because freeing handles or growing WASM\n * memory invalidates borrowed views.\n */\nexport class WasmBridge {\n private readonly encoder = new TextEncoder();\n private disposed = false;\n\n private constructor(private readonly exports: WasmExports, private readonly context: number) {}\n\n /** Instantiates the expected ABI, creates a context, and registers its fonts. */\n static async create(wasmUrl: string | URL, fonts: readonly FontRegistration[] = []): Promise<WasmBridge> {\n const response = await fetch(wasmUrl);\n if (!response.ok) throw new WasmRenderError(`Could not load WASM: HTTP ${response.status}`, -10);\n\n let result: WebAssembly.WebAssemblyInstantiatedSource;\n try {\n result = await WebAssembly.instantiateStreaming(response.clone(), {});\n } catch {\n result = await WebAssembly.instantiate(await response.arrayBuffer(), {});\n }\n\n const exports = result.instance.exports as unknown as WasmExports;\n const abiVersion = exports.html2realpdf_abi_version?.();\n if (abiVersion !== EXPECTED_ABI_VERSION) {\n throw new WasmRenderError(`Unsupported WASM ABI version ${String(abiVersion)}; expected ${EXPECTED_ABI_VERSION}`, -14);\n }\n const context = exports.pdf_context_create();\n if (context === 0) throw new WasmRenderError(\"WASM context allocation failed\", -12);\n const bridge = new WasmBridge(exports, context);\n try {\n for (const registration of fonts) bridge.registerFont(registration);\n return bridge;\n } catch (error) {\n bridge.dispose();\n throw error;\n }\n }\n\n /** Serializes render options, invokes the native renderer, and returns owned output. */\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile: CssProfile = \"document\", marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[]): WasmRenderResult {\n if (this.disposed) throw new WasmRenderError(\"WASM bridge has been disposed\", -15);\n const input = this.encoder.encode(html);\n const renderOptions = this.encoder.encode(JSON.stringify({\n pageWidthPoints: page.widthPoints,\n pageHeightPoints: page.heightPoints,\n marginTopPoints: page.marginTopPoints,\n marginRightPoints: page.marginRightPoints,\n marginBottomPoints: page.marginBottomPoints,\n marginLeftPoints: page.marginLeftPoints,\n cssProfile,\n marginBoxes,\n pageRules,\n metadata: metadata ? {\n ...metadata,\n keywords: Array.isArray(metadata.keywords) ? metadata.keywords.join(\", \") : metadata.keywords,\n } : undefined,\n }));\n const inputPointer = this.exports.alloc(input.length);\n if (inputPointer === 0) throw new WasmRenderError(\"WASM input allocation failed\", -11);\n const optionsPointer = this.exports.alloc(renderOptions.length);\n if (optionsPointer === 0) {\n this.exports.free(inputPointer, input.length);\n throw new WasmRenderError(\"WASM options allocation failed\", -11);\n }\n\n let resultHandle = 0;\n try {\n new Uint8Array(this.exports.memory.buffer, inputPointer, input.length).set(input);\n new Uint8Array(this.exports.memory.buffer, optionsPointer, renderOptions.length).set(renderOptions);\n resultHandle = this.exports.render_html_to_pdf_with_context_json_options(\n this.context,\n inputPointer,\n input.length,\n optionsPointer,\n renderOptions.length,\n );\n if (resultHandle === 0) throw new WasmRenderError(\"WASM result allocation failed\", -12);\n\n const status = this.exports.pdf_result_status(resultHandle);\n if (status !== 0) {\n const detail = this.readResultString(resultHandle, \"error\");\n throw new WasmRenderError(detail || `WASM PDF rendering failed with status ${status}`, status);\n }\n\n const pointer = this.exports.pdf_result_data_ptr(resultHandle);\n const length = this.exports.pdf_result_data_len(resultHandle);\n if (pointer === 0 || length === 0) throw new WasmRenderError(\"WASM returned an empty PDF\", -13);\n\n return {\n bytes: new Uint8Array(this.exports.memory.buffer, pointer, length).slice(),\n pageCount: this.exports.pdf_result_page_count(resultHandle),\n diagnostics: this.readDiagnostics(resultHandle),\n };\n } finally {\n if (resultHandle !== 0) this.exports.pdf_result_free(resultHandle);\n this.exports.free(inputPointer, input.length);\n this.exports.free(optionsPointer, renderOptions.length);\n }\n }\n\n /** Frees the renderer context and every font copied into it. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.exports.pdf_context_free(this.context);\n }\n\n /** Copies one font registration across the ABI into context-owned storage. */\n private registerFont(registration: FontRegistration): void {\n const family = this.encoder.encode(registration.family.trim());\n const data = registration.data instanceof Uint8Array\n ? registration.data\n : new Uint8Array(registration.data);\n if (family.length === 0 || data.length === 0) throw new WasmRenderError(\"Font family and data must not be empty\", -16);\n const familyPointer = this.exports.alloc(family.length);\n const dataPointer = this.exports.alloc(data.length);\n if (familyPointer === 0 || dataPointer === 0) {\n if (familyPointer !== 0) this.exports.free(familyPointer, family.length);\n if (dataPointer !== 0) this.exports.free(dataPointer, data.length);\n throw new WasmRenderError(\"WASM font allocation failed\", -11);\n }\n try {\n new Uint8Array(this.exports.memory.buffer, familyPointer, family.length).set(family);\n new Uint8Array(this.exports.memory.buffer, dataPointer, data.length).set(data);\n const numericWeight = registration.weight === \"bold\" ? 700 : registration.weight === \"normal\" || registration.weight === undefined\n ? 400\n : registration.weight;\n const status = this.exports.pdf_context_register_font(\n this.context,\n familyPointer,\n family.length,\n dataPointer,\n data.length,\n numericWeight,\n registration.style === \"italic\" ? 1 : 0,\n );\n if (status !== 0) throw new WasmRenderError(`WASM font registration failed with status ${status}`, status);\n } finally {\n this.exports.free(familyPointer, family.length);\n this.exports.free(dataPointer, data.length);\n }\n }\n\n private readResultString(handle: number, kind: \"error\" | \"diagnostics\"): string {\n const pointer = kind === \"error\"\n ? this.exports.pdf_result_error_ptr(handle)\n : this.exports.pdf_result_diagnostics_ptr(handle);\n const length = kind === \"error\"\n ? this.exports.pdf_result_error_len(handle)\n : this.exports.pdf_result_diagnostics_len(handle);\n if (pointer === 0 || length === 0) return \"\";\n return new TextDecoder().decode(new Uint8Array(this.exports.memory.buffer, pointer, length));\n }\n\n private readDiagnostics(handle: number): Diagnostic[] {\n const serialized = this.readResultString(handle, \"diagnostics\");\n if (!serialized) return [];\n try {\n const parsed: unknown = JSON.parse(serialized);\n return Array.isArray(parsed) ? parsed as Diagnostic[] : [];\n } catch {\n return [{ code: \"INVALID_WASM_DIAGNOSTICS\", severity: \"warning\", message: \"WASM returned malformed diagnostics\" }];\n }\n }\n}\n"]}
@@ -0,0 +1 @@
1
+ export {};
package/dist/worker.js ADDED
@@ -0,0 +1,30 @@
1
+ /// <reference lib="webworker" />
2
+ /**
3
+ * Module Worker protocol that owns a `WasmBridge` off the browser main thread.
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ import { WasmBridge } from "./wasm.js";
8
+ const scope = self;
9
+ let bridgePromise;
10
+ // Initialization and renders share the same promise so early render requests
11
+ // wait for font registration instead of racing the native context.
12
+ scope.addEventListener("message", (event) => {
13
+ const message = event.data;
14
+ if (message.type === "init") {
15
+ bridgePromise = WasmBridge.create(message.wasmUrl, message.fonts);
16
+ bridgePromise.then(() => scope.postMessage({ type: "ready" }), (error) => scope.postMessage({ type: "init-error", error: errorMessage(error) }));
17
+ return;
18
+ }
19
+ if (!bridgePromise) {
20
+ scope.postMessage({ type: "render-error", id: message.id, error: "Worker is not initialized" });
21
+ return;
22
+ }
23
+ bridgePromise.then((bridge) => bridge.render(message.html, message.page, message.metadata, message.cssProfile, message.marginBoxes, message.pageRules)).then((result) => {
24
+ scope.postMessage({ type: "render-result", id: message.id, bytes: result.bytes, pageCount: result.pageCount, diagnostics: result.diagnostics }, [result.bytes.buffer]);
25
+ }, (error) => scope.postMessage({ type: "render-error", id: message.id, error: errorMessage(error) }));
26
+ });
27
+ function errorMessage(error) {
28
+ return error instanceof Error ? error.message : String(error);
29
+ }
30
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,iCAAiC;AAEjC;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAwBvC,MAAM,KAAK,GAAG,IAA6C,CAAC;AAC5D,IAAI,aAA8C,CAAC;AAEnD,6EAA6E;AAC7E,mEAAmE;AACnE,KAAK,CAAC,gBAAgB,CAAC,SAAS,EAAE,CAAC,KAAgD,EAAE,EAAE;IACrF,MAAM,OAAO,GAAG,KAAK,CAA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AAK,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAC5G,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/// <reference lib=\"webworker\" />\n\n/**\n * Module Worker protocol that owns a `WasmBridge` off the browser main thread.\n *\n * @packageDocumentation\n */\n\nimport { WasmBridge } from \"./wasm.js\";\nimport type { NormalizedPage } from \"./page.js\";\nimport type { CssProfile, FontRegistration, PdfMetadata } from \"./types.js\";\nimport type { SnapshotPageMarginBox, SnapshotPageRule } from \"./snapshot.js\";\n\n/** Creates the single renderer context owned by this Worker. */\ninterface InitMessage {\n type: \"init\";\n wasmUrl: string;\n fonts: readonly FontRegistration[];\n}\n\n/** Requests one render and correlates its transferable result by `id`. */\ninterface RenderMessage {\n type: \"render\";\n id: number;\n html: string;\n page: NormalizedPage;\n metadata?: PdfMetadata;\n cssProfile?: CssProfile;\n marginBoxes?: readonly SnapshotPageMarginBox[];\n pageRules?: readonly SnapshotPageRule[];\n}\n\nconst scope = self as unknown as DedicatedWorkerGlobalScope;\nlet bridgePromise: Promise<WasmBridge> | undefined;\n\n// Initialization and renders share the same promise so early render requests\n// wait for font registration instead of racing the native context.\nscope.addEventListener(\"message\", (event: MessageEvent<InitMessage | RenderMessage>) => {\n const message = event.data;\n if (message.type === \"init\") {\n bridgePromise = WasmBridge.create(message.wasmUrl, message.fonts);\n bridgePromise.then(\n () => scope.postMessage({ type: \"ready\" }),\n (error: unknown) => scope.postMessage({ type: \"init-error\", error: errorMessage(error) }),\n );\n return;\n }\n\n if (!bridgePromise) {\n scope.postMessage({ type: \"render-error\", id: message.id, error: \"Worker is not initialized\" });\n return;\n }\n\n bridgePromise.then((bridge) => bridge.render(message.html, message.page, message.metadata, message.cssProfile, message.marginBoxes, message.pageRules)).then(\n (result) => {\n scope.postMessage(\n { type: \"render-result\", id: message.id, bytes: result.bytes, pageCount: result.pageCount, diagnostics: result.diagnostics },\n [result.bytes.buffer],\n );\n },\n (error: unknown) => scope.postMessage({ type: \"render-error\", id: message.id, error: errorMessage(error) }),\n );\n});\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@imggion/html2realpdf",
3
+ "version": "0.1.0",
4
+ "description": "Browser-first HTML to real, selectable PDF rendering powered by Zig and WebAssembly",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "skills"
18
+ ],
19
+ "sideEffects": false,
20
+ "scripts": {
21
+ "clean": "node ./scripts/clean.mjs",
22
+ "build": "node ./scripts/build.mjs && tsc -p tsconfig.json && node ./scripts/prepare-browser-build.mjs",
23
+ "build:small": "node ./scripts/build.mjs --release-small && tsc -p tsconfig.json && node ./scripts/prepare-browser-build.mjs",
24
+ "build:bindings": "node ./scripts/build.mjs --skip-wasm-build && tsc -p tsconfig.json && node ./scripts/prepare-browser-build.mjs",
25
+ "test": "npm run build && node --test ./test/*.test.mjs && node ./scripts/verify-package.mjs --types-only",
26
+ "test:consumer": "npm run build && node ./scripts/verify-package.mjs",
27
+ "prepack": "npm run build"
28
+ },
29
+ "keywords": [
30
+ "html",
31
+ "pdf",
32
+ "wasm",
33
+ "webassembly",
34
+ "typescript",
35
+ "react"
36
+ ],
37
+ "license": "MIT",
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/imggion/html2realpdf.git"
41
+ },
42
+ "homepage": "https://github.com/imggion/html2realpdf#readme",
43
+ "bugs": {
44
+ "url": "https://github.com/imggion/html2realpdf/issues"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public",
48
+ "provenance": true
49
+ },
50
+ "engines": {
51
+ "node": ">=20.16.0"
52
+ },
53
+ "devDependencies": {
54
+ "pdfjs-dist": "5.4.624",
55
+ "typescript": "^7.0.2"
56
+ }
57
+ }
@@ -0,0 +1,260 @@
1
+ ---
2
+ name: html2realpdf
3
+ description: Integrate and troubleshoot @imggion/html2realpdf in browser TypeScript or JavaScript projects. Use when rendering HTML strings, DOM elements, or React-compatible refs to selectable PDFs; configuring pages, resources, fonts, SVG or canvas output; previewing, downloading, or exporting PDFs; inspecting diagnostics; or migrating supported html2pdf.js chains.
4
+ ---
5
+
6
+ # Use html2realpdf
7
+
8
+ Install the ESM package and import only from its public root:
9
+
10
+ ```sh
11
+ npm install @imggion/html2realpdf
12
+ ```
13
+
14
+ The module is safe to import during SSR, but call rendering APIs only in a
15
+ browser. Do not deep-import `dist` files or construct exported result classes.
16
+
17
+ ## Choose the API
18
+
19
+ - Use `renderPdf` for convenient page-lifetime rendering.
20
+ - Use `createRenderer` for repeated renders, custom fonts, explicit Worker
21
+ selection, or deterministic disposal.
22
+ - Use the default export only when adapting a supported html2pdf.js chain.
23
+ - Prefer a mounted `Element` or ref-shaped `{ current }` value when computed
24
+ styles, form state, pseudo-elements, canvas pixels, or Shadow DOM matter.
25
+
26
+ ```ts
27
+ import { renderPdf, type RenderOptions } from "@imggion/html2realpdf";
28
+
29
+ const options: RenderOptions = {
30
+ page: { format: "a4", unit: "mm", margin: [15, 12] },
31
+ cssProfile: "web",
32
+ mediaType: "print",
33
+ fallback: "error",
34
+ };
35
+
36
+ const pdf = await renderPdf(document.querySelector("#invoice")!, options);
37
+ try {
38
+ pdf.download("invoice.pdf");
39
+ console.table(pdf.diagnostics);
40
+ } finally {
41
+ pdf.dispose();
42
+ }
43
+ ```
44
+
45
+ Treat four-value margins as `[top, left, bottom, right]`, matching the
46
+ html2pdf.js compatibility API rather than CSS shorthand order.
47
+
48
+ ## Configuration reference
49
+
50
+ Use these tables as the quick option reference. Treat the package's generated
51
+ TypeScript declarations as authoritative when the installed version differs.
52
+
53
+ ### Renderer lifetime
54
+
55
+ Pass only renderer-owned resources and execution settings to `createRenderer`:
56
+
57
+ | Option | Values and default | Use |
58
+ | --- | --- | --- |
59
+ | `execution` | `"worker"` (default) or `"main"` | Keep synchronous WASM work off the UI thread unless Worker execution is unavailable. |
60
+ | `wasmUrl` | `string \| URL`; package-relative WASM by default | Override only when deployment cannot serve the bundled asset. |
61
+ | `fonts` | `FontRegistration[]`; none by default | Register reusable TrueType faces once for every render owned by this renderer. |
62
+
63
+ Configure each font registration with `family`, binary `data`, optional
64
+ `weight` (`400` by default, or `"normal"`/`"bold"`), and optional `style`
65
+ (`"normal"` by default or `"italic"`).
66
+
67
+ ### Per-render options
68
+
69
+ Pass these options to `renderPdf` or `renderer.render`:
70
+
71
+ | Option | Values and default | Use |
72
+ | --- | --- | --- |
73
+ | `page` | Captured `@page`, otherwise A4 portrait with zero margins | Override captured page geometry explicitly. See page settings below. |
74
+ | `cssProfile` | `"document"` (default), `"web"`, or `"strict"` | Select stable report layout, broader browser layout, or broader layout with rejection defaults. |
75
+ | `strict` | `false` | Promote unsupported snapshot CSS to errors without selecting the web profile. Explicit `unsupportedCss` wins. |
76
+ | `mediaType` | `"screen"` (default) or `"print"` | Select the media environment used for computed styles and media queries. |
77
+ | `layoutContext` | `"source"` (default) or `"page"` | Preserve the mounted root width or reflow an implicit root width and auto inline margins against the PDF content box. |
78
+ | `viewport` | `{ width, height }`; source environment by default | Make responsive layout deterministic in CSS pixels. |
79
+ | `unsupportedCss` | `"warn"` (default), `"error"`, or `"ignore"`; strict modes default to `"error"` | Choose whether unsupported CSS records diagnostics, rejects, or is omitted silently. |
80
+ | `fallback` | `"error"` (default) or `"rasterize-subtree"` | Keep unsupported SVG native-only or allow explicit scoped rasterization. |
81
+ | `canvasToSvg` | Adapter function; none by default | Convert live canvas charts to validated SVG through the source library's exporter. |
82
+ | `canvasFallback` | `"error"` (default) or `"rasterize"` | Handle an intentional `null` result from `canvasToSvg`; thrown or malformed output still rejects. |
83
+ | `includeShadowDom` | `false` | Flatten open Shadow DOM into the snapshot; closed roots remain inaccessible. |
84
+ | `baseUrl` | `string \| URL`; source document URL by default | Resolve relative image and stylesheet URLs. |
85
+ | `resourcePolicy` | `"error"` (default) or `"omit"` | Reject failed resources or omit them with diagnostics. |
86
+ | `resourceResolver` | Resolver function; none by default | Supply protected or virtual images and stylesheets. Register fonts on the renderer instead. |
87
+ | `pageBreak` | `PageBreakRules`; none by default | Add selector-driven pagination overrides while retaining authored CSS breaks. |
88
+ | `metadata` | `PdfMetadata`; none by default | Write `title`, `author`, `subject`, `keywords`, and `creator` into the PDF information dictionary. |
89
+ | `enableLinks` | `true` | Preserve PDF link annotations; set `false` to remove captured link targets. |
90
+ | `signal` | `AbortSignal`; none by default | Cancel at snapshot and render boundaries; synchronous WASM already in progress cannot be preempted. |
91
+ | `onProgress` | Callback; none by default | Receive coarse `snapshot`, `wasm`, and `complete` phase updates, not per-page progress. |
92
+
93
+ Configure explicit `page` geometry with:
94
+
95
+ | Page option | Values and default |
96
+ | --- | --- |
97
+ | `format` | `"a4"` (default), `"letter"`, or custom `[width, height]` |
98
+ | `orientation` | `"portrait"` (default) or `"landscape"` |
99
+ | `unit` | `"pt"` (default), `"px"`, `"mm"`, `"cm"`, or `"in"` |
100
+ | `margin` | One number, `[vertical, horizontal]`, or `[top, left, bottom, right]`; zero by default |
101
+
102
+ Named formats retain their physical dimensions regardless of `unit`; custom
103
+ dimensions and margins use the selected unit. Reject margins that leave no
104
+ positive content area.
105
+
106
+ Configure `pageBreak` with selector strings or arrays in `before`, `after`, and
107
+ `avoid`. Set `avoidAll: true` to apply `break-inside: avoid` globally. Set
108
+ `legacy: true` to honor `.html2pdf__page-break`. Authored inline `!important`
109
+ break declarations retain precedence.
110
+
111
+ ### Preview options
112
+
113
+ Pass these options to `PdfDocument.preview`:
114
+
115
+ | Option | Values and default |
116
+ | --- | --- |
117
+ | `initialScale` | `"fit-width"` (default) or a numeric scale |
118
+ | `minScale` | `0.25` by default, clamped to at least `0.1` |
119
+ | `maxScale` | `3` by default, clamped to at least `minScale` |
120
+ | `zoomStep` | `0.25` by default, clamped to at least `0.05` |
121
+ | `maxPixelRatio` | `2` by default; caps page-canvas device pixel ratio |
122
+ | `ariaLabel` | `"PDF preview"` by default |
123
+ | `onProgress` | Callback after each page canvas completes |
124
+
125
+ ### html2pdf.js compatibility options
126
+
127
+ Use the default export only for this supported PDF-oriented option subset:
128
+
129
+ | Option | Values and default | Compatibility |
130
+ | --- | --- | --- |
131
+ | `margin` | Same one-, two-, or four-value forms as modern `page.margin` | Supported |
132
+ | `filename` | `"file.pdf"` | Used by `save` when no method argument is supplied. |
133
+ | `enableLinks` | `true` | Supported |
134
+ | `pagebreak.mode` | `"css"`, `"legacy"`, `"avoid-all"`, or an array; `css` and `legacy` when the `pagebreak` object omits `mode` | Supported; authored CSS breaks remain native. |
135
+ | `pagebreak.before` / `after` / `avoid` | Selector string or array | Supported |
136
+ | `jsPDF.unit` | `"mm"` by compatibility default; modern supported units only | Supported |
137
+ | `jsPDF.format` | `"a4"`, `"letter"`, or custom dimensions | Supported |
138
+ | `jsPDF.orientation` | `"portrait"` or `"landscape"` | Supported |
139
+ | `html2canvas` | No supported value | Reject explicitly; there is no full-page canvas pipeline. |
140
+ | `image` | No supported value | Reject explicitly; PDF pages are not encoded as raster images. |
141
+
142
+ ## Reuse a renderer
143
+
144
+ Register embeddable TrueType fonts during renderer creation. Keep the renderer
145
+ for a batch of documents, then dispose it.
146
+
147
+ ```ts
148
+ import { createRenderer } from "@imggion/html2realpdf";
149
+
150
+ const renderer = await createRenderer({
151
+ execution: "worker",
152
+ fonts: [{
153
+ family: "Inter",
154
+ data: await (await fetch("/fonts/Inter-Regular.ttf")).arrayBuffer(),
155
+ weight: 400,
156
+ style: "normal",
157
+ }],
158
+ });
159
+
160
+ try {
161
+ const pdf = await renderer.render(
162
+ '<p style="font-family: Inter">Selectable text</p>',
163
+ );
164
+ try {
165
+ const blob = pdf.toBlob();
166
+ // Store or upload blob.
167
+ } finally {
168
+ pdf.dispose();
169
+ }
170
+ } finally {
171
+ renderer.dispose();
172
+ }
173
+ ```
174
+
175
+ Use `execution: "main"` only when Worker execution is unavailable. Override
176
+ `wasmUrl` only for a deployment that cannot serve package-relative assets.
177
+
178
+ ## Preview and export
179
+
180
+ Use `toBlob`, `toArrayBuffer`, or `toUint8Array` for application-owned output.
181
+ Use `createObjectURL` with `revokeObjectURL` when managing a URL manually.
182
+ Dispose previews before their document, or let `PdfDocument.dispose()` dispose
183
+ all previews it owns.
184
+
185
+ ```ts
186
+ const preview = await pdf.preview(document.querySelector("#preview")!, {
187
+ initialScale: "fit-width",
188
+ });
189
+
190
+ preview.dispose();
191
+ pdf.dispose();
192
+ ```
193
+
194
+ ## Resolve resources and browser state
195
+
196
+ - Set `baseUrl` for relative URLs.
197
+ - Use `resourceResolver` for images and stylesheets that cannot be fetched
198
+ directly. Register fonts through `createRenderer`, not the resolver.
199
+ - Remember that stylesheets in HTML-string input are inert unless the resolver
200
+ supplies them.
201
+ - Inspect `pdf.diagnostics`; use `strict`, `unsupportedCss`, and
202
+ `fallback: "error"` when unsupported output must fail.
203
+ - Opt into `fallback: "rasterize-subtree"` only for the affected unsupported
204
+ SVG subtree. Never describe the result as fully vector after fallback.
205
+ - Check an `AbortSignal` result normally, but do not assume an already-running
206
+ synchronous WASM render can be preempted.
207
+
208
+ For a live canvas chart, prefer the chart library's SVG exporter:
209
+
210
+ ```ts
211
+ const pdf = await renderer.render(dashboardElement, {
212
+ canvasToSvg: ({ canvas, cssWidth, cssHeight }) =>
213
+ chartFor(canvas).toSvg({ width: cssWidth, height: cssHeight }),
214
+ canvasFallback: "error",
215
+ fallback: "error",
216
+ });
217
+ ```
218
+
219
+ ## Use React refs
220
+
221
+ Keep the package framework-agnostic. Call it from client-side code after the
222
+ ref is mounted; do not add React as a wrapper dependency.
223
+
224
+ ```tsx
225
+ const reportRef = useRef<HTMLDivElement>(null);
226
+
227
+ async function downloadReport() {
228
+ if (!reportRef.current) return;
229
+ const pdf = await renderPdf(reportRef, { cssProfile: "web" });
230
+ try {
231
+ pdf.download("report.pdf");
232
+ } finally {
233
+ pdf.dispose();
234
+ }
235
+ }
236
+ ```
237
+
238
+ ## Migrate html2pdf.js chains
239
+
240
+ Use only PDF-oriented compatibility stages:
241
+
242
+ ```ts
243
+ import html2pdf from "@imggion/html2realpdf";
244
+
245
+ await html2pdf()
246
+ .set({
247
+ filename: "invoice.pdf",
248
+ margin: [10, 12],
249
+ jsPDF: { format: "a4", unit: "mm", orientation: "portrait" },
250
+ })
251
+ .from(document.querySelector("#invoice")!)
252
+ .save();
253
+ ```
254
+
255
+ Do not use `toCanvas`, `toImg`, `outputImg`, canvas/image input stages,
256
+ `html2canvas` options, or raster `image` options. They throw
257
+ `UnsupportedCompatibilityFeatureError` by design.
258
+
259
+ Use the package's generated declarations as the complete option and return-type
260
+ reference. Keep examples aligned with public root exports.
@@ -0,0 +1,4 @@
1
+ interface:
2
+ display_name: "html2realpdf"
3
+ short_description: "Build selectable PDFs from browser HTML"
4
+ default_prompt: "Use $html2realpdf to integrate typed browser HTML-to-PDF rendering in this project."