@imggion/html2realpdf 0.2.0 → 0.3.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 +65 -3
- package/dist/LICENSE.md +16 -0
- package/dist/attachments.d.ts +15 -0
- package/dist/attachments.js +73 -0
- package/dist/attachments.js.map +1 -0
- package/dist/compat.js +6 -0
- package/dist/compat.js.map +1 -1
- package/dist/libhtml2realpdf.wasm +0 -0
- package/dist/renderer.js +14 -5
- package/dist/renderer.js.map +1 -1
- package/dist/types.d.ts +23 -0
- package/dist/types.js.map +1 -1
- package/dist/wasm.d.ts +2 -1
- package/dist/wasm.js +35 -30
- package/dist/wasm.js.map +1 -1
- package/dist/worker.js +1 -6
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/skills/html2realpdf/SKILL.md +28 -0
package/README.md
CHANGED
|
@@ -6,8 +6,14 @@
|
|
|
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.
|
|
10
|
-
<img src="https://img.shields.io/badge/release-0.
|
|
9
|
+
<a href="https://github.com/imggion/html2realpdf/releases/tag/v0.3.0">
|
|
10
|
+
<img src="https://img.shields.io/badge/release-0.3.0-2ea44f?style=flat-square" alt="Latest release: 0.3.0">
|
|
11
|
+
</a>
|
|
12
|
+
<a href="#compliance">
|
|
13
|
+
<img src="https://img.shields.io/badge/PDF%2FA--3u-d32f2f?style=flat-square&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSJub25lIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTE0IDJINXYyMGgxNFY3ek0xNCAydjVoNSIvPjx0ZXh0IHg9IjEyIiB5PSIxNyIgZmlsbD0id2hpdGUiIGZvbnQtZmFtaWx5PSJBcmlhbCxzYW5zLXNlcmlmIiBmb250LXNpemU9IjciIGZvbnQtd2VpZ2h0PSJib2xkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QREY8L3RleHQ%2BPC9zdmc%2B" alt="PDF/A-3u">
|
|
14
|
+
</a>
|
|
15
|
+
<a href="#compliance">
|
|
16
|
+
<img src="https://img.shields.io/badge/PDF%2FA--3b-d32f2f?style=flat-square&logo=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0Ij48cGF0aCBmaWxsPSJub25lIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjEuNSIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIgZD0iTTE0IDJINXYyMGgxNFY3ek0xNCAydjVoNSIvPjx0ZXh0IHg9IjEyIiB5PSIxNyIgZmlsbD0id2hpdGUiIGZvbnQtZmFtaWx5PSJBcmlhbCxzYW5zLXNlcmlmIiBmb250LXNpemU9IjciIGZvbnQtd2VpZ2h0PSJib2xkIiB0ZXh0LWFuY2hvcj0ibWlkZGxlIj5QREY8L3RleHQ%2BPC9zdmc%2B" alt="PDF/A-3b">
|
|
11
17
|
</a>
|
|
12
18
|
<img src="https://img.shields.io/badge/-zig-f39b34?style=flat-square&logo=zig&logoColor=white" alt="Zig">
|
|
13
19
|
<img src="https://img.shields.io/badge/-WASM-654ff0?style=flat-square&logo=webassembly&logoColor=white" alt="WebAssembly">
|
|
@@ -28,6 +34,8 @@
|
|
|
28
34
|
- [Vue](#vue)
|
|
29
35
|
- [Preview](#preview)
|
|
30
36
|
- [Page layouts](#page-layouts)
|
|
37
|
+
- [PDF/A and attachments](#pdfa-and-attachments)
|
|
38
|
+
- [Compliance](#compliance)
|
|
31
39
|
- [Benchmark](#benchmark)
|
|
32
40
|
- [Contributing](#contributing)
|
|
33
41
|
- [License](#license)
|
|
@@ -206,6 +214,58 @@ const pdf = await renderPdf(postcard, {
|
|
|
206
214
|
});
|
|
207
215
|
```
|
|
208
216
|
|
|
217
|
+
## PDF/A and attachments
|
|
218
|
+
|
|
219
|
+
Opt into PDF/A-3u independently of the CSS profile:
|
|
220
|
+
|
|
221
|
+
```ts
|
|
222
|
+
const pdf = await renderPdf(invoice, {
|
|
223
|
+
conformance: "pdfa-3u",
|
|
224
|
+
metadata: { title: "Invoice" },
|
|
225
|
+
attachments: [{
|
|
226
|
+
name: "invoice.xml",
|
|
227
|
+
data: new TextEncoder().encode(xml),
|
|
228
|
+
mimeType: "application/xml",
|
|
229
|
+
relationship: "Data",
|
|
230
|
+
}],
|
|
231
|
+
});
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
The writer embeds sRGB, synchronized XMP metadata and Unicode font mappings.
|
|
235
|
+
Incompatible resources produce an error; there is no fallback to ordinary PDF.
|
|
236
|
+
CMYK JPEGs, missing glyphs and fonts that forbid outline embedding are rejected.
|
|
237
|
+
Transparency and supported SVG remain native PDF graphics. This is PDF/A-3u,
|
|
238
|
+
not a claim of Tagged PDF, PDF/UA, digital signatures or Factur-X compliance.
|
|
239
|
+
|
|
240
|
+
Attachments also work without `conformance`. Their bytes are preserved, and
|
|
241
|
+
caller buffers stay usable in both Worker and main-thread execution. MIME type
|
|
242
|
+
defaults to `application/octet-stream` and relationship to `Unspecified`.
|
|
243
|
+
Optional `description` and `modifiedAt: Date` are supported; dates are never
|
|
244
|
+
invented. Empty/duplicate names, malformed MIME types and invalid dates fail.
|
|
245
|
+
The html2pdf.js adapter accepts the same options through `.set(...)`.
|
|
246
|
+
|
|
247
|
+
See [PDF/A implementation and validation](https://github.com/imggion/html2realpdf/blob/main/docs/pdfa.md)
|
|
248
|
+
for limits and the pinned veraPDF gate. Existing calls without these options
|
|
249
|
+
keep their ordinary PDF output.
|
|
250
|
+
|
|
251
|
+
## Compliance
|
|
252
|
+
|
|
253
|
+
<p align="center">
|
|
254
|
+
<img src="https://raw.githubusercontent.com/imggion/html2realpdf/bacb5d0c1f8e240593c4813c4e78cf529f48e710/docs/assets/pdfa-3u-validation.png" alt="veraPDF 1.30.2 report for test.pdf: PDF/A-3u validation passed, with 14,749 passed checks and zero failed checks." width="600">
|
|
255
|
+
</p>
|
|
256
|
+
|
|
257
|
+
Try it yourself: render a document with `conformance: "pdfa-3u"`, download it,
|
|
258
|
+
and open it in [veraPDF](https://verapdf.org/), or check both profiles with its
|
|
259
|
+
[CLI](https://docs.verapdf.org/cli/validation/):
|
|
260
|
+
|
|
261
|
+
```sh
|
|
262
|
+
verapdf --flavour 3u --format text invoice.pdf
|
|
263
|
+
verapdf --flavour 3b --format text invoice.pdf
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
To run the repository's PDF/A-3u validation suite, use `make test-pdfa` after
|
|
267
|
+
completing the [contributor setup](#contributing).
|
|
268
|
+
|
|
209
269
|
## Benchmark
|
|
210
270
|
|
|
211
271
|
One recorded run of the deterministic 30-page stress report produced:
|
|
@@ -224,7 +284,8 @@ One recorded run of the deterministic 30-page stress report produced:
|
|
|
224
284
|
|
|
225
285
|
## Contributing
|
|
226
286
|
|
|
227
|
-
You need Zig `0.16.0`, Node.js `20.16+`, npm, and Make.
|
|
287
|
+
You need Zig `0.16.0`, Node.js `20.16+`, npm, and Make. The PDF/A gate
|
|
288
|
+
also needs Java 17+, Poppler, curl and unzip. On a fresh checkout,
|
|
228
289
|
install the JavaScript dependencies once:
|
|
229
290
|
|
|
230
291
|
```sh
|
|
@@ -240,6 +301,7 @@ npm ci --prefix tests/web
|
|
|
240
301
|
| `make wasm` | Build the default `ReleaseFast` WebAssembly and browser package |
|
|
241
302
|
| `make wasm-small` | Build the optional size-oriented `ReleaseSmall` package asset |
|
|
242
303
|
| `make react` | Start the React integration app |
|
|
304
|
+
| `make test-pdfa` | Validate PDF/A-3u with veraPDF 1.30.2 and benchmark 30 pages |
|
|
243
305
|
| `make test-release` | Run the complete release gate |
|
|
244
306
|
|
|
245
307
|
To open the small browser test harness:
|
package/dist/LICENSE.md
CHANGED
|
@@ -463,3 +463,19 @@ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
|
|
|
463
463
|
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
|
464
464
|
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
|
465
465
|
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
## ICC sRGB2014 profile
|
|
469
|
+
|
|
470
|
+
Asset: `src/assets/color/sRGB2014.icc` (unmodified, February 2015 revision).
|
|
471
|
+
Source: https://registry.color.org/rgb-registry/profiles/sRGB2014.icc
|
|
472
|
+
SHA-256: `384b832de3412066743b52a75ee906b6fb9fb8d9e09e936fc2c43223815c6e0a`
|
|
473
|
+
Copyright International Color Consortium.
|
|
474
|
+
|
|
475
|
+
This profile is made available by the International Color Consortium, and may
|
|
476
|
+
be copied, distributed, embedded, made, used, and sold without restriction.
|
|
477
|
+
Altered versions of this profile shall have the original identification and
|
|
478
|
+
copyright information removed and shall not be misrepresented as the original
|
|
479
|
+
profile.
|
|
480
|
+
|
|
481
|
+
License source: https://registry.color.org/profile-library/
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { PdfAttachment, RenderOptions } from "./types.js";
|
|
2
|
+
export interface PreparedAttachment {
|
|
3
|
+
name: string;
|
|
4
|
+
data: Uint8Array<ArrayBuffer>;
|
|
5
|
+
mimeType: string;
|
|
6
|
+
relationship: NonNullable<PdfAttachment["relationship"]>;
|
|
7
|
+
description?: string;
|
|
8
|
+
modifiedAt?: string;
|
|
9
|
+
}
|
|
10
|
+
export interface PdfExtras {
|
|
11
|
+
conformance?: RenderOptions["conformance"];
|
|
12
|
+
attachments?: readonly PreparedAttachment[];
|
|
13
|
+
}
|
|
14
|
+
/** Copies just the supplied views, keeping caller buffers usable after Worker transfer. */
|
|
15
|
+
export declare function preparePdfExtras(options: Pick<RenderOptions, "conformance" | "attachments">): PdfExtras;
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/** Render-local attachment ownership and validation shared by both backends. */
|
|
2
|
+
import { WasmRenderError } from "./errors.js";
|
|
3
|
+
/** Copies just the supplied views, keeping caller buffers usable after Worker transfer. */
|
|
4
|
+
export function preparePdfExtras(options) {
|
|
5
|
+
if (options.conformance !== undefined && options.conformance !== "pdfa-3u") {
|
|
6
|
+
fail("Unsupported PDF conformance");
|
|
7
|
+
}
|
|
8
|
+
const result = {};
|
|
9
|
+
if (options.conformance !== undefined)
|
|
10
|
+
result.conformance = options.conformance;
|
|
11
|
+
if (options.attachments === undefined)
|
|
12
|
+
return result;
|
|
13
|
+
if (!Array.isArray(options.attachments))
|
|
14
|
+
fail("Attachments must be an array");
|
|
15
|
+
const names = new Set();
|
|
16
|
+
result.attachments = options.attachments.map((attachment) => {
|
|
17
|
+
if (!attachment || typeof attachment.name !== "string" || !attachment.name.trim()) {
|
|
18
|
+
fail("Attachment name must not be empty");
|
|
19
|
+
}
|
|
20
|
+
validateString(attachment.name);
|
|
21
|
+
if (names.has(attachment.name))
|
|
22
|
+
fail(`Duplicate attachment name: ${attachment.name}`);
|
|
23
|
+
names.add(attachment.name);
|
|
24
|
+
const mimeType = attachment.mimeType === undefined ? "application/octet-stream" : attachment.mimeType;
|
|
25
|
+
if (typeof mimeType !== "string" ||
|
|
26
|
+
!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(mimeType)) {
|
|
27
|
+
fail("Invalid attachment MIME type");
|
|
28
|
+
}
|
|
29
|
+
const relationship = attachment.relationship === undefined ? "Unspecified" : attachment.relationship;
|
|
30
|
+
if (!["Source", "Data", "Alternative", "Supplement", "Unspecified"].includes(relationship)) {
|
|
31
|
+
fail("Invalid attachment relationship");
|
|
32
|
+
}
|
|
33
|
+
if (!(attachment.data instanceof ArrayBuffer) && !(attachment.data instanceof Uint8Array)) {
|
|
34
|
+
fail("Attachment data must be an ArrayBuffer or Uint8Array");
|
|
35
|
+
}
|
|
36
|
+
// Copy only the supplied view so Worker transfer cannot detach the caller's buffer.
|
|
37
|
+
let data;
|
|
38
|
+
try {
|
|
39
|
+
data = new Uint8Array(attachment.data instanceof Uint8Array ? attachment.data : new Uint8Array(attachment.data));
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return fail("Attachment buffer is detached or invalid");
|
|
43
|
+
}
|
|
44
|
+
const prepared = { name: attachment.name, data, mimeType, relationship };
|
|
45
|
+
if (attachment.description !== undefined) {
|
|
46
|
+
validateString(attachment.description);
|
|
47
|
+
prepared.description = attachment.description;
|
|
48
|
+
}
|
|
49
|
+
if (attachment.modifiedAt !== undefined) {
|
|
50
|
+
const date = attachment.modifiedAt;
|
|
51
|
+
if (!(date instanceof Date) ||
|
|
52
|
+
!Number.isFinite(date.getTime()) ||
|
|
53
|
+
date.getUTCFullYear() < 1 ||
|
|
54
|
+
date.getUTCFullYear() > 9999) {
|
|
55
|
+
fail("Invalid attachment modification date");
|
|
56
|
+
}
|
|
57
|
+
prepared.modifiedAt = `D:${date.toISOString().slice(0, 19).replace(/[-:T]/g, "")}Z`;
|
|
58
|
+
}
|
|
59
|
+
return prepared;
|
|
60
|
+
});
|
|
61
|
+
return result;
|
|
62
|
+
}
|
|
63
|
+
function validateString(value) {
|
|
64
|
+
if (typeof value !== "string")
|
|
65
|
+
fail("Attachment text must be a string");
|
|
66
|
+
for (const character of value) {
|
|
67
|
+
const cp = character.codePointAt(0);
|
|
68
|
+
if (cp === 0 || cp === 0xfffe || cp === 0xffff || (cp >= 0xd800 && cp <= 0xdfff))
|
|
69
|
+
fail("Invalid attachment Unicode text");
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function fail(message) { throw new WasmRenderError(message, -4); }
|
|
73
|
+
//# sourceMappingURL=attachments.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attachments.js","sourceRoot":"","sources":["../src/attachments.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAiB9C,2FAA2F;AAC3F,MAAM,UAAU,gBAAgB,CAAC,OAA2D;IAC1F,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;QAC3E,IAAI,CAAC,6BAA6B,CAAC,CAAC;IACtC,CAAC;IAED,MAAM,MAAM,GAAc,EAAE,CAAC;IAC7B,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS;QAAE,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;IAEhF,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS;QAAE,OAAO,MAAM,CAAC;IACrD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC;QAAE,IAAI,CAAC,8BAA8B,CAAC,CAAC;IAE9E,MAAM,KAAK,GAAG,IAAI,GAAG,EAAU,CAAC;IAChC,MAAM,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAsB,EAAE;QAC9E,IAAI,CAAC,UAAU,IAAI,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC;YAClF,IAAI,CAAC,mCAAmC,CAAC,CAAC;QAC5C,CAAC;QACD,cAA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KAAK,MAAM,IAAI,EAAE,KAAK,MAAM,IAAI,CAAC,EAAE,IAAI,MAAM,IAAI,EAAE,IAAI,MAAM,CAAC;YAAE,IAAI,CAAC,iCAAiC,CAAC,CAAC;IAC5H,CAAC;AACH,CAAC;AAED,SAAS,IAAI,CAAC,OAAe,IAAW,MAAM,IAAI,eAAe,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC","sourcesContent":["/** Render-local attachment ownership and validation shared by both backends. */\nimport { WasmRenderError } from \"./errors.js\";\nimport type { PdfAttachment, RenderOptions } from \"./types.js\";\n\nexport interface PreparedAttachment {\n name: string;\n data: Uint8Array<ArrayBuffer>;\n mimeType: string;\n relationship: NonNullable<PdfAttachment[\"relationship\"]>;\n description?: string;\n modifiedAt?: string;\n}\n\nexport interface PdfExtras {\n conformance?: RenderOptions[\"conformance\"];\n attachments?: readonly PreparedAttachment[];\n}\n\n/** Copies just the supplied views, keeping caller buffers usable after Worker transfer. */\nexport function preparePdfExtras(options: Pick<RenderOptions, \"conformance\" | \"attachments\">): PdfExtras {\n if (options.conformance !== undefined && options.conformance !== \"pdfa-3u\") {\n fail(\"Unsupported PDF conformance\");\n }\n\n const result: PdfExtras = {};\n if (options.conformance !== undefined) result.conformance = options.conformance;\n\n if (options.attachments === undefined) return result;\n if (!Array.isArray(options.attachments)) fail(\"Attachments must be an array\");\n\n const names = new Set<string>();\n result.attachments = options.attachments.map((attachment): PreparedAttachment => {\n if (!attachment || typeof attachment.name !== \"string\" || !attachment.name.trim()) {\n fail(\"Attachment name must not be empty\");\n }\n validateString(attachment.name);\n if (names.has(attachment.name)) fail(`Duplicate attachment name: ${attachment.name}`);\n names.add(attachment.name);\n\n const mimeType = attachment.mimeType === undefined ? \"application/octet-stream\" : attachment.mimeType;\n if (\n typeof mimeType !== \"string\" ||\n !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(mimeType)\n ) {\n fail(\"Invalid attachment MIME type\");\n }\n\n const relationship = attachment.relationship === undefined ? \"Unspecified\" : attachment.relationship;\n if (![\"Source\", \"Data\", \"Alternative\", \"Supplement\", \"Unspecified\"].includes(relationship)) {\n fail(\"Invalid attachment relationship\");\n }\n\n if (!(attachment.data instanceof ArrayBuffer) && !(attachment.data instanceof Uint8Array)) {\n fail(\"Attachment data must be an ArrayBuffer or Uint8Array\");\n }\n\n // Copy only the supplied view so Worker transfer cannot detach the caller's buffer.\n let data: Uint8Array<ArrayBuffer>;\n try {\n data = new Uint8Array(\n attachment.data instanceof Uint8Array ? attachment.data : new Uint8Array(attachment.data),\n );\n } catch {\n return fail(\"Attachment buffer is detached or invalid\");\n }\n\n const prepared: PreparedAttachment = { name: attachment.name, data, mimeType, relationship };\n\n if (attachment.description !== undefined) {\n validateString(attachment.description);\n prepared.description = attachment.description;\n }\n\n if (attachment.modifiedAt !== undefined) {\n const date = attachment.modifiedAt;\n if (\n !(date instanceof Date) ||\n !Number.isFinite(date.getTime()) ||\n date.getUTCFullYear() < 1 ||\n date.getUTCFullYear() > 9999\n ) {\n fail(\"Invalid attachment modification date\");\n }\n prepared.modifiedAt = `D:${date.toISOString().slice(0, 19).replace(/[-:T]/g, \"\")}Z`;\n }\n\n return prepared;\n });\n\n return result;\n}\n\nfunction validateString(value: string): void {\n if (typeof value !== \"string\") fail(\"Attachment text must be a string\");\n for (const character of value) {\n const cp = character.codePointAt(0)!;\n if (cp === 0 || cp === 0xfffe || cp === 0xffff || (cp >= 0xd800 && cp <= 0xdfff)) fail(\"Invalid attachment Unicode text\");\n }\n}\n\nfunction fail(message: string): never { throw new WasmRenderError(message, -4); }\n"]}
|
package/dist/compat.js
CHANGED
|
@@ -184,6 +184,12 @@ function compatRenderOptions(options) {
|
|
|
184
184
|
if (options.margin !== undefined)
|
|
185
185
|
page.margin = options.margin;
|
|
186
186
|
const renderOptions = { page };
|
|
187
|
+
if (options.metadata !== undefined)
|
|
188
|
+
renderOptions.metadata = options.metadata;
|
|
189
|
+
if (options.conformance !== undefined)
|
|
190
|
+
renderOptions.conformance = options.conformance;
|
|
191
|
+
if (options.attachments !== undefined)
|
|
192
|
+
renderOptions.attachments = options.attachments;
|
|
187
193
|
if (options.enableLinks !== undefined)
|
|
188
194
|
renderOptions.enableLinks = options.enableLinks;
|
|
189
195
|
if (options.pagebreak) {
|
package/dist/compat.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"compat.js","sourceRoot":"","sources":["../src/compat.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,oCAAoC,EAAE,MAAM,aAAa,CAAC;AACnE,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAG1C;;;;;;;GAOG;AACH,MAAM,OAAO,YAAY;IACf,MAAM,CAAc;IACpB,OAAO,GAAoB,EAAE,CAAC;IAC9B,UAAU,CAAmC;IAC7C,IAAI,GAAqB,OAAO,CAAC,OAAO,EAAE,CAAC;IAEnD,2EAA2E;IAC3E,IAAI,CAAC,MAAkB,EAAE,IAA8C;QACrE,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,KAAK,EAAE,CAAC;YACxC,MAAM,IAAI,oCAAoC,CAAC,aAAa,IAAI,GAAG,CAAC,CAAC;QACvE,CAAC;QACD,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,oFAAoF;IACpF,GAAG,CAAC,OAAwB;QAC1B,IAAI,OAAO,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;YACtC,MAAM,IAAI,oCAAoC,CAAC,qBAAqB,CAAC,CAAC;QACxE,CAAC;QACD,IAAI,OAAO,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;YAChC,MAAM,IAAI,oCAAoC,CAAC,eAAe,CAAC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AM,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7E,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * PDF-oriented html2pdf.js compatibility chain over the native renderer.\n *\n * @packageDocumentation\n */\n\nimport { UnsupportedCompatibilityFeatureError } from \"./errors.js\";\nimport { PdfDocument } from \"./pdf-document.js\";\nimport { renderPdf } from \"./renderer.js\";\nimport type { Html2PdfOptions, HtmlSource, PageOptions, PdfOutputType, RenderOptions } from \"./types.js\";\n\n/**\n * Stateful, Promise-like compatibility chain.\n *\n * @remarks\n * The worker caches one `PdfDocument` until its source or options change.\n * Raster-only html2pdf.js stages fail explicitly rather than silently changing\n * the native PDF model.\n */\nexport class CompatWorker implements PromiseLike<PdfDocument> {\n private source?: HtmlSource;\n private options: Html2PdfOptions = {};\n private pdfPromise: Promise<PdfDocument> | undefined;\n private tail: Promise<unknown> = Promise.resolve();\n\n /** Sets the HTML source; canvas and image input stages are unsupported. */\n from(source: HtmlSource, type?: \"string\" | \"element\" | \"canvas\" | \"img\"): this {\n if (type === \"canvas\" || type === \"img\") {\n throw new UnsupportedCompatibilityFeatureError(`from(..., ${type})`);\n }\n this.source = source;\n this.pdfPromise = undefined;\n return this;\n }\n\n /** Shallow-merges supported compatibility options and invalidates cached output. */\n set(options: Html2PdfOptions): this {\n if (options.html2canvas !== undefined) {\n throw new UnsupportedCompatibilityFeatureError(\"html2canvas options\");\n }\n if (options.image !== undefined) {\n throw new UnsupportedCompatibilityFeatureError(\"image options\");\n }\n this.options = { ...this.options, ...options };\n this.pdfPromise = undefined;\n return this;\n }\n\n /** Alias for `set`, retained for html2pdf.js chain compatibility. */\n using(options: Html2PdfOptions): this {\n return this.set(options);\n }\n\n /**\n * Advances to PDF output for `pdf` or `container` targets.\n *\n * @remarks\n * The wrapper has no public intermediate container. A `container` target\n * therefore schedules the PDF directly; canvas and image targets throw.\n */\n to(target: \"pdf\" | \"container\" | \"canvas\" | \"img\"): this {\n if (target === \"pdf\" || target === \"container\") return this.toPdf();\n throw new UnsupportedCompatibilityFeatureError(`to(${target})`);\n }\n\n /** Schedules PDF rendering while preserving the fluent chain. */\n toPdf(): this {\n this.tail = this.ensurePdf();\n return this;\n }\n\n /** Compatibility no-op; no intermediate snapshot container is exposed. */\n toContainer(): this {\n return this;\n }\n\n /** Always throws because full-page canvas output is intentionally unsupported. */\n toCanvas(): never {\n throw new UnsupportedCompatibilityFeatureError(\"toCanvas\");\n }\n\n /** Always throws because raster image output is intentionally unsupported. */\n toImg(): never {\n throw new UnsupportedCompatibilityFeatureError(\"toImg\");\n }\n\n /** Schedules a browser download using the explicit or configured filename. */\n save(filename = this.options.filename ?? \"file.pdf\"): this {\n this.tail = this.ensurePdf().then((pdf) => pdf.download(filename));\n return this;\n }\n\n /** Alias for `save`. */\n saveAs(filename?: string): this {\n return this.save(filename);\n }\n\n /**\n * Resolves PDF output in a compatibility encoding.\n *\n * @remarks\n * Blob URL outputs remain owned by the cached `PdfDocument`. Obtain it with\n * `get(\"pdf\")` to revoke the URL, or dispose the document when finished.\n */\n outputPdf(type?: \"blob\"): Promise<Blob>;\n outputPdf(type: \"arraybuffer\"): Promise<ArrayBuffer>;\n outputPdf(type: StringPdfOutputType): Promise<string>;\n outputPdf(type: PdfOutputType): Promise<ArrayBuffer | Blob | string>;\n async outputPdf(type: PdfOutputType = \"blob\"): Promise<ArrayBuffer | Blob | string> {\n const pdf = await this.ensurePdf();\n switch (type) {\n case \"arraybuffer\": return pdf.toArrayBuffer();\n case \"blob\": return pdf.toBlob();\n case \"bloburl\":\n case \"bloburi\": return pdf.createObjectURL();\n case \"datauristring\":\n case \"dataurlstring\": return blobToDataUrl(pdf.toBlob());\n }\n }\n\n /** Routes generic html2pdf.js output requests to PDF output. */\n output(type?: \"blob\", options?: unknown, source?: \"pdf\"): Promise<Blob>;\n output(type: \"arraybuffer\", options?: unknown, source?: \"pdf\"): Promise<ArrayBuffer>;\n output(type: StringPdfOutputType, options?: unknown, source?: \"pdf\"): Promise<string>;\n output(type: PdfOutputType | undefined, options: unknown, source: \"img\"): Promise<never>;\n output(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string>;\n output(type?: PdfOutputType, _options?: unknown, source: \"pdf\" | \"img\" = \"pdf\"): Promise<ArrayBuffer | Blob | string> {\n if (source === \"img\") return Promise.reject(new UnsupportedCompatibilityFeatureError(\"outputImg\"));\n return type === undefined ? this.outputPdf() : this.outputPdf(type);\n }\n\n /** Alias for `output`. */\n export(type?: \"blob\", options?: unknown, source?: \"pdf\"): Promise<Blob>;\n export(type: \"arraybuffer\", options?: unknown, source?: \"pdf\"): Promise<ArrayBuffer>;\n export(type: StringPdfOutputType, options?: unknown, source?: \"pdf\"): Promise<string>;\n export(type: PdfOutputType | undefined, options: unknown, source: \"img\"): Promise<never>;\n export(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string>;\n export(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string> {\n return this.output(type, options, source);\n }\n\n /** Returns a rejected promise because raster image output is unsupported. */\n outputImg(): Promise<never> {\n return Promise.reject(new UnsupportedCompatibilityFeatureError(\"outputImg\"));\n }\n\n /**\n * Resolves the cached PDF for `pdf`, or a configured compatibility option for\n * any other key, then optionally invokes the legacy callback.\n */\n get(key: string, callback?: (value: unknown) => void): Promise<unknown> {\n const value = key === \"pdf\" ? this.ensurePdf() : Promise.resolve(this.options[key as keyof Html2PdfOptions]);\n return value.then((resolved) => {\n callback?.(resolved);\n return resolved;\n });\n }\n\n /** Interrupts a chain by throwing the supplied message as an `Error`. */\n error(message: string): never {\n throw new Error(message);\n }\n\n /** Makes the chain awaitable and resolves it to the cached `PdfDocument`. */\n then<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.tail.then(() => this.ensurePdf()).then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n thenCore<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n thenExternal<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n run<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Handles a failed chain while preserving `PdfDocument` as the success type. */\n catch<TResult = never>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<PdfDocument | TResult> {\n return this.then(undefined, onRejected);\n }\n\n /** Compatibility alias for `catch`. */\n catchExternal<TResult = never>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<PdfDocument | TResult> {\n return this.catch(onRejected);\n }\n\n private ensurePdf(): Promise<PdfDocument> {\n if (!this.source) return Promise.reject(new Error(\"No HTML source was provided\"));\n this.pdfPromise ??= renderPdf(this.source, compatRenderOptions(this.options));\n return this.pdfPromise;\n }\n}\n\n/**\n * Creates an html2pdf.js-compatible PDF chain.\n *\n * @remarks\n * Passing a source directly preserves html2pdf.js shorthand behavior and also\n * schedules `save`. Call without a source when composing an explicit chain.\n *\n * @example\n * ```ts\n * await html2pdf()\n * .set({ filename: \"invoice.pdf\", margin: [10, 12] })\n * .from(element)\n * .save();\n * ```\n */\nexport default function html2pdf(source?: HtmlSource, options?: Html2PdfOptions): CompatWorker {\n const worker = new CompatWorker();\n if (options) worker.set(options);\n if (source) worker.from(source).save();\n return worker;\n}\n\nhtml2pdf.Worker = CompatWorker;\n\nfunction compatRenderOptions(options: Html2PdfOptions): RenderOptions {\n const page: PageOptions = { unit: options.jsPDF?.unit ?? \"mm\" };\n if (options.jsPDF?.format !== undefined) page.format = options.jsPDF.format;\n if (options.jsPDF?.orientation !== undefined) page.orientation = options.jsPDF.orientation;\n if (options.margin !== undefined) page.margin = options.margin;\n\n const renderOptions: RenderOptions = { page };\n if (options.enableLinks !== undefined) renderOptions.enableLinks = options.enableLinks;\n if (options.pagebreak) {\n const modes = typeof options.pagebreak.mode === \"string\"\n ? [options.pagebreak.mode]\n : options.pagebreak.mode ?? [\"css\", \"legacy\"];\n const pageBreak: NonNullable<RenderOptions[\"pageBreak\"]> = {\n legacy: modes.includes(\"legacy\"),\n avoidAll: modes.includes(\"avoid-all\"),\n };\n if (options.pagebreak.before !== undefined) pageBreak.before = options.pagebreak.before;\n if (options.pagebreak.after !== undefined) pageBreak.after = options.pagebreak.after;\n if (options.pagebreak.avoid !== undefined) pageBreak.avoid = options.pagebreak.avoid;\n renderOptions.pageBreak = pageBreak;\n }\n return renderOptions;\n}\n\ntype StringPdfOutputType = Exclude<PdfOutputType, \"arraybuffer\" | \"blob\">;\n\nfunction blobToDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.addEventListener(\"load\", () => resolve(String(reader.result)), { once: true });\n reader.addEventListener(\"error\", () => reject(reader.error), { once: true });\n reader.readAsDataURL(blob);\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"compat.js","source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,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7E,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * PDF-oriented html2pdf.js compatibility chain over the native renderer.\n *\n * @packageDocumentation\n */\n\nimport { UnsupportedCompatibilityFeatureError } from \"./errors.js\";\nimport { PdfDocument } from \"./pdf-document.js\";\nimport { renderPdf } from \"./renderer.js\";\nimport type { Html2PdfOptions, HtmlSource, PageOptions, PdfOutputType, RenderOptions } from \"./types.js\";\n\n/**\n * Stateful, Promise-like compatibility chain.\n *\n * @remarks\n * The worker caches one `PdfDocument` until its source or options change.\n * Raster-only html2pdf.js stages fail explicitly rather than silently changing\n * the native PDF model.\n */\nexport class CompatWorker implements PromiseLike<PdfDocument> {\n private source?: HtmlSource;\n private options: Html2PdfOptions = {};\n private pdfPromise: Promise<PdfDocument> | undefined;\n private tail: Promise<unknown> = Promise.resolve();\n\n /** Sets the HTML source; canvas and image input stages are unsupported. */\n from(source: HtmlSource, type?: \"string\" | \"element\" | \"canvas\" | \"img\"): this {\n if (type === \"canvas\" || type === \"img\") {\n throw new UnsupportedCompatibilityFeatureError(`from(..., ${type})`);\n }\n this.source = source;\n this.pdfPromise = undefined;\n return this;\n }\n\n /** Shallow-merges supported compatibility options and invalidates cached output. */\n set(options: Html2PdfOptions): this {\n if (options.html2canvas !== undefined) {\n throw new UnsupportedCompatibilityFeatureError(\"html2canvas options\");\n }\n if (options.image !== undefined) {\n throw new UnsupportedCompatibilityFeatureError(\"image options\");\n }\n this.options = { ...this.options, ...options };\n this.pdfPromise = undefined;\n return this;\n }\n\n /** Alias for `set`, retained for html2pdf.js chain compatibility. */\n using(options: Html2PdfOptions): this {\n return this.set(options);\n }\n\n /**\n * Advances to PDF output for `pdf` or `container` targets.\n *\n * @remarks\n * The wrapper has no public intermediate container. A `container` target\n * therefore schedules the PDF directly; canvas and image targets throw.\n */\n to(target: \"pdf\" | \"container\" | \"canvas\" | \"img\"): this {\n if (target === \"pdf\" || target === \"container\") return this.toPdf();\n throw new UnsupportedCompatibilityFeatureError(`to(${target})`);\n }\n\n /** Schedules PDF rendering while preserving the fluent chain. */\n toPdf(): this {\n this.tail = this.ensurePdf();\n return this;\n }\n\n /** Compatibility no-op; no intermediate snapshot container is exposed. */\n toContainer(): this {\n return this;\n }\n\n /** Always throws because full-page canvas output is intentionally unsupported. */\n toCanvas(): never {\n throw new UnsupportedCompatibilityFeatureError(\"toCanvas\");\n }\n\n /** Always throws because raster image output is intentionally unsupported. */\n toImg(): never {\n throw new UnsupportedCompatibilityFeatureError(\"toImg\");\n }\n\n /** Schedules a browser download using the explicit or configured filename. */\n save(filename = this.options.filename ?? \"file.pdf\"): this {\n this.tail = this.ensurePdf().then((pdf) => pdf.download(filename));\n return this;\n }\n\n /** Alias for `save`. */\n saveAs(filename?: string): this {\n return this.save(filename);\n }\n\n /**\n * Resolves PDF output in a compatibility encoding.\n *\n * @remarks\n * Blob URL outputs remain owned by the cached `PdfDocument`. Obtain it with\n * `get(\"pdf\")` to revoke the URL, or dispose the document when finished.\n */\n outputPdf(type?: \"blob\"): Promise<Blob>;\n outputPdf(type: \"arraybuffer\"): Promise<ArrayBuffer>;\n outputPdf(type: StringPdfOutputType): Promise<string>;\n outputPdf(type: PdfOutputType): Promise<ArrayBuffer | Blob | string>;\n async outputPdf(type: PdfOutputType = \"blob\"): Promise<ArrayBuffer | Blob | string> {\n const pdf = await this.ensurePdf();\n switch (type) {\n case \"arraybuffer\": return pdf.toArrayBuffer();\n case \"blob\": return pdf.toBlob();\n case \"bloburl\":\n case \"bloburi\": return pdf.createObjectURL();\n case \"datauristring\":\n case \"dataurlstring\": return blobToDataUrl(pdf.toBlob());\n }\n }\n\n /** Routes generic html2pdf.js output requests to PDF output. */\n output(type?: \"blob\", options?: unknown, source?: \"pdf\"): Promise<Blob>;\n output(type: \"arraybuffer\", options?: unknown, source?: \"pdf\"): Promise<ArrayBuffer>;\n output(type: StringPdfOutputType, options?: unknown, source?: \"pdf\"): Promise<string>;\n output(type: PdfOutputType | undefined, options: unknown, source: \"img\"): Promise<never>;\n output(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string>;\n output(type?: PdfOutputType, _options?: unknown, source: \"pdf\" | \"img\" = \"pdf\"): Promise<ArrayBuffer | Blob | string> {\n if (source === \"img\") return Promise.reject(new UnsupportedCompatibilityFeatureError(\"outputImg\"));\n return type === undefined ? this.outputPdf() : this.outputPdf(type);\n }\n\n /** Alias for `output`. */\n export(type?: \"blob\", options?: unknown, source?: \"pdf\"): Promise<Blob>;\n export(type: \"arraybuffer\", options?: unknown, source?: \"pdf\"): Promise<ArrayBuffer>;\n export(type: StringPdfOutputType, options?: unknown, source?: \"pdf\"): Promise<string>;\n export(type: PdfOutputType | undefined, options: unknown, source: \"img\"): Promise<never>;\n export(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string>;\n export(type?: PdfOutputType, options?: unknown, source?: \"pdf\" | \"img\"): Promise<ArrayBuffer | Blob | string> {\n return this.output(type, options, source);\n }\n\n /** Returns a rejected promise because raster image output is unsupported. */\n outputImg(): Promise<never> {\n return Promise.reject(new UnsupportedCompatibilityFeatureError(\"outputImg\"));\n }\n\n /**\n * Resolves the cached PDF for `pdf`, or a configured compatibility option for\n * any other key, then optionally invokes the legacy callback.\n */\n get(key: string, callback?: (value: unknown) => void): Promise<unknown> {\n const value = key === \"pdf\" ? this.ensurePdf() : Promise.resolve(this.options[key as keyof Html2PdfOptions]);\n return value.then((resolved) => {\n callback?.(resolved);\n return resolved;\n });\n }\n\n /** Interrupts a chain by throwing the supplied message as an `Error`. */\n error(message: string): never {\n throw new Error(message);\n }\n\n /** Makes the chain awaitable and resolves it to the cached `PdfDocument`. */\n then<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.tail.then(() => this.ensurePdf()).then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n thenCore<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n thenExternal<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Compatibility alias for `then`. */\n run<TResult1 = PdfDocument, TResult2 = never>(\n onFulfilled?: ((value: PdfDocument) => TResult1 | PromiseLike<TResult1>) | null,\n onRejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null,\n ): Promise<TResult1 | TResult2> {\n return this.then(onFulfilled, onRejected);\n }\n\n /** Handles a failed chain while preserving `PdfDocument` as the success type. */\n catch<TResult = never>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<PdfDocument | TResult> {\n return this.then(undefined, onRejected);\n }\n\n /** Compatibility alias for `catch`. */\n catchExternal<TResult = never>(onRejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | null): Promise<PdfDocument | TResult> {\n return this.catch(onRejected);\n }\n\n private ensurePdf(): Promise<PdfDocument> {\n if (!this.source) return Promise.reject(new Error(\"No HTML source was provided\"));\n this.pdfPromise ??= renderPdf(this.source, compatRenderOptions(this.options));\n return this.pdfPromise;\n }\n}\n\n/**\n * Creates an html2pdf.js-compatible PDF chain.\n *\n * @remarks\n * Passing a source directly preserves html2pdf.js shorthand behavior and also\n * schedules `save`. Call without a source when composing an explicit chain.\n *\n * @example\n * ```ts\n * await html2pdf()\n * .set({ filename: \"invoice.pdf\", margin: [10, 12] })\n * .from(element)\n * .save();\n * ```\n */\nexport default function html2pdf(source?: HtmlSource, options?: Html2PdfOptions): CompatWorker {\n const worker = new CompatWorker();\n if (options) worker.set(options);\n if (source) worker.from(source).save();\n return worker;\n}\n\nhtml2pdf.Worker = CompatWorker;\n\nfunction compatRenderOptions(options: Html2PdfOptions): RenderOptions {\n const page: PageOptions = { unit: options.jsPDF?.unit ?? \"mm\" };\n if (options.jsPDF?.format !== undefined) page.format = options.jsPDF.format;\n if (options.jsPDF?.orientation !== undefined) page.orientation = options.jsPDF.orientation;\n if (options.margin !== undefined) page.margin = options.margin;\n\n const renderOptions: RenderOptions = { page };\n if (options.metadata !== undefined) renderOptions.metadata = options.metadata;\n if (options.conformance !== undefined) renderOptions.conformance = options.conformance;\n if (options.attachments !== undefined) renderOptions.attachments = options.attachments;\n if (options.enableLinks !== undefined) renderOptions.enableLinks = options.enableLinks;\n if (options.pagebreak) {\n const modes = typeof options.pagebreak.mode === \"string\"\n ? [options.pagebreak.mode]\n : options.pagebreak.mode ?? [\"css\", \"legacy\"];\n const pageBreak: NonNullable<RenderOptions[\"pageBreak\"]> = {\n legacy: modes.includes(\"legacy\"),\n avoidAll: modes.includes(\"avoid-all\"),\n };\n if (options.pagebreak.before !== undefined) pageBreak.before = options.pagebreak.before;\n if (options.pagebreak.after !== undefined) pageBreak.after = options.pagebreak.after;\n if (options.pagebreak.avoid !== undefined) pageBreak.avoid = options.pagebreak.avoid;\n renderOptions.pageBreak = pageBreak;\n }\n return renderOptions;\n}\n\ntype StringPdfOutputType = Exclude<PdfOutputType, \"arraybuffer\" | \"blob\">;\n\nfunction blobToDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.addEventListener(\"load\", () => resolve(String(reader.result)), { once: true });\n reader.addEventListener(\"error\", () => reject(reader.error), { once: true });\n reader.readAsDataURL(blob);\n });\n}\n"]}
|
|
Binary file
|
package/dist/renderer.js
CHANGED
|
@@ -7,6 +7,7 @@ import { UnsupportedEnvironmentError, WasmRenderError } from "./errors.js";
|
|
|
7
7
|
import { normalizePage } from "./page.js";
|
|
8
8
|
import { PdfDocument } from "./pdf-document.js";
|
|
9
9
|
import { snapshotSource } from "./snapshot.js";
|
|
10
|
+
import { preparePdfExtras } from "./attachments.js";
|
|
10
11
|
import { WasmBridge } from "./wasm.js";
|
|
11
12
|
/** Executes the synchronous bridge on the caller's browser thread. */
|
|
12
13
|
class MainThreadBackend {
|
|
@@ -14,10 +15,10 @@ class MainThreadBackend {
|
|
|
14
15
|
constructor(bridge) {
|
|
15
16
|
this.bridge = bridge;
|
|
16
17
|
}
|
|
17
|
-
render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal) {
|
|
18
|
+
render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal, extras) {
|
|
18
19
|
if (signal?.aborted)
|
|
19
20
|
return Promise.reject(abortReason(signal));
|
|
20
|
-
return Promise.resolve(this.bridge.render(html, page, metadata, cssProfile, marginBoxes, pageRules));
|
|
21
|
+
return Promise.resolve(this.bridge.render(html, page, metadata, cssProfile, marginBoxes, pageRules, extras));
|
|
21
22
|
}
|
|
22
23
|
dispose() {
|
|
23
24
|
this.bridge.dispose();
|
|
@@ -63,7 +64,7 @@ class WorkerBackend {
|
|
|
63
64
|
});
|
|
64
65
|
this.worker.postMessage({ type: "init", wasmUrl, fonts });
|
|
65
66
|
}
|
|
66
|
-
async render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal) {
|
|
67
|
+
async render(html, page, metadata, cssProfile, marginBoxes, pageRules, signal, extras) {
|
|
67
68
|
if (this.disposed)
|
|
68
69
|
throw new Error("Renderer has been disposed");
|
|
69
70
|
if (signal?.aborted)
|
|
@@ -81,7 +82,14 @@ class WorkerBackend {
|
|
|
81
82
|
pending.removeAbort = () => signal.removeEventListener("abort", onAbort);
|
|
82
83
|
}
|
|
83
84
|
this.pending.set(id, pending);
|
|
84
|
-
|
|
85
|
+
try {
|
|
86
|
+
this.worker.postMessage({ type: "render", id, html, page, metadata, cssProfile, marginBoxes, pageRules, extras }, extras?.attachments?.map((attachment) => attachment.data.buffer) ?? []);
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
this.pending.delete(id);
|
|
90
|
+
pending.removeAbort?.();
|
|
91
|
+
reject(error);
|
|
92
|
+
}
|
|
85
93
|
});
|
|
86
94
|
}
|
|
87
95
|
dispose() {
|
|
@@ -146,6 +154,7 @@ export class Html2RealPdf {
|
|
|
146
154
|
throw new Error("Renderer has been disposed");
|
|
147
155
|
if (options.signal?.aborted)
|
|
148
156
|
throw abortReason(options.signal);
|
|
157
|
+
const extras = preparePdfExtras(options);
|
|
149
158
|
options.onProgress?.({ phase: "snapshot", completed: 0, total: 1 });
|
|
150
159
|
const snapshotOptions = {
|
|
151
160
|
resourcePolicy: options.resourcePolicy ?? "error",
|
|
@@ -183,7 +192,7 @@ export class Html2RealPdf {
|
|
|
183
192
|
options.onProgress?.({ phase: "snapshot", completed: 1, total: 1 });
|
|
184
193
|
options.onProgress?.({ phase: "wasm", completed: 0, total: 1 });
|
|
185
194
|
const page = options.page !== undefined ? normalizePage(options.page) : snapshot.page ?? normalizePage();
|
|
186
|
-
const rendered = await this.backend.render(applyPageBreakRules(snapshot.html, options.pageBreak), page, options.metadata, options.cssProfile ?? "document", snapshot.pageMarginBoxes, options.page === undefined ? snapshot.pageRules : undefined, options.signal);
|
|
195
|
+
const rendered = await this.backend.render(applyPageBreakRules(snapshot.html, options.pageBreak), page, options.metadata, options.cssProfile ?? "document", snapshot.pageMarginBoxes, options.page === undefined ? snapshot.pageRules : undefined, options.signal, extras);
|
|
187
196
|
options.onProgress?.({ phase: "wasm", completed: 1, total: 1 });
|
|
188
197
|
options.onProgress?.({ phase: "complete", completed: 1, total: 1 });
|
|
189
198
|
return PdfDocument.create(rendered.bytes, rendered.pageCount, [...snapshot.diagnostics, ...rendered.diagnostics]);
|
package/dist/renderer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,2BAA2B,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAuB,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAA2E,MAAM,eAAe,CAAC;AAExH,OAAO,EAAE,UAAU,EAAyB,MAAM,WAAW,CAAC;AAQ9D,sEAAsE;AACtE,MAAM,iBAAiB;IACQ,MAAM;IAAnC,YAA6B,MAAkB;sBAAlB,MAAM;IAAe,CAAC;IAEnD,MAAM,CAAC,IAAY,EAAE,IAAoB,EAAE,QAAsB,EAAE,UAAuB,EAAE,WAA8C,EAAE,SAAuC,EAAE,MAAoB;QACvM,IAAI,MAAM,EAAE,OAAO;YAAE,OAAO,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;QAChE,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC,CAAC;IACvG,CAAC;IAED,OAAO;QACL,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;CACF;AASD,gFAAgF;AAChF,MAAM,aAAa;IACA,MAAM,CAAS;IACf,OAAO,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC3C,KAAK,CAAgB;IAC9B,MAAM,GAAG,CAAC,CAAC;IACX,QAAQ,GAAG,KAAK,CAAC;IAEzB,YAAY,OAAe,EAAE,KAAkC;QAC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QAAQ;QAAE,YAAY,CAAC,IAAI,CAAC,sCAAsC,CAAC,CAAC;IAC9E,OAAO,YAAY,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,sCAAsC,YAAY,CAAC,IAAI,CAAC,EAAE,CAAC,WAAW,IAAI,EAAE,CAAC;AACzH,CAAC;AAED,SAAS,kBAAkB,CAAC,MAAgB,EAAE,KAA6C,EAAE,WAAmB;IAC9G,MAAM,SAAS,GAAG,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;IACpE,MAAM,IAAI,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;IACpH,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,WAAW,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAS,WAAW,CAAC,MAAmB;IACtC,OAAO,MAAM,CAAC,MAAM,IAAI,IAAI,YAAY,CAAC,2BAA2B,EAAE,YAAY,CAAC,CAAC;AACtF,CAAC","sourcesContent":["/**\n * Renderer factories, execution backends, and per-render pipeline ownership.\n *\n * @packageDocumentation\n */\n\nimport { UnsupportedEnvironmentError, WasmRenderError } from \"./errors.js\";\nimport { normalizePage, type NormalizedPage } from \"./page.js\";\nimport { PdfDocument } from \"./pdf-document.js\";\nimport { snapshotSource, type SnapshotOptions, type SnapshotPageMarginBox, type SnapshotPageRule } from \"./snapshot.js\";\nimport type { CssProfile, FontRegistration, HtmlSource, PageBreakRules, PdfMetadata, RendererInit, RenderOptions } from \"./types.js\";\nimport { WasmBridge, type WasmRenderResult } from \"./wasm.js\";\n\n/** Common ownership boundary for main-thread and Worker WASM contexts. */\ninterface Backend {\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal): Promise<WasmRenderResult>;\n dispose(): void;\n}\n\n/** Executes the synchronous bridge on the caller's browser thread. */\nclass MainThreadBackend implements Backend {\n constructor(private readonly bridge: WasmBridge) {}\n\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal): Promise<WasmRenderResult> {\n if (signal?.aborted) return Promise.reject(abortReason(signal));\n return Promise.resolve(this.bridge.render(html, page, metadata, cssProfile, marginBoxes, pageRules));\n }\n\n dispose(): void {\n this.bridge.dispose();\n }\n}\n\n/** Caller state retained while a Worker render is in flight. */\ninterface PendingRender {\n resolve: (result: WasmRenderResult) => void;\n reject: (error: unknown) => void;\n removeAbort?: () => void;\n}\n\n/** Owns a module Worker and routes concurrent results by request identifier. */\nclass WorkerBackend implements Backend {\n private readonly worker: Worker;\n private readonly pending = new Map<number, PendingRender>();\n private readonly ready: Promise<void>;\n private nextId = 1;\n private disposed = false;\n\n constructor(wasmUrl: string, fonts: readonly FontRegistration[]) {\n this.worker = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\", name: \"html2realpdf\" });\n this.ready = new Promise<void>((resolve, reject) => {\n const onError = (event: ErrorEvent) => {\n this.worker.removeEventListener(\"message\", onMessage);\n reject(new WasmRenderError(event.message || \"PDF Worker initialization failed\", -20));\n };\n const onMessage = (event: MessageEvent) => {\n if (event.data?.type === \"ready\") {\n this.worker.removeEventListener(\"message\", onMessage);\n this.worker.removeEventListener(\"error\", onError);\n resolve();\n } else if (event.data?.type === \"init-error\") {\n this.worker.removeEventListener(\"message\", onMessage);\n this.worker.removeEventListener(\"error\", onError);\n reject(new WasmRenderError(event.data.error, -20));\n }\n };\n this.worker.addEventListener(\"message\", onMessage);\n this.worker.addEventListener(\"error\", onError, { once: true });\n });\n this.worker.addEventListener(\"message\", (event) => this.handleMessage(event));\n this.worker.addEventListener(\"error\", (event) => {\n const error = new WasmRenderError(event.message || \"PDF Worker failed\", -22);\n for (const pending of this.pending.values()) {\n pending.removeAbort?.();\n pending.reject(error);\n }\n this.pending.clear();\n });\n this.worker.postMessage({ type: \"init\", wasmUrl, fonts });\n }\n\n async render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal): Promise<WasmRenderResult> {\n if (this.disposed) throw new Error(\"Renderer has been disposed\");\n if (signal?.aborted) throw abortReason(signal);\n await this.ready;\n\n const id = this.nextId++;\n return new Promise<WasmRenderResult>((resolve, reject) => {\n const pending: PendingRender = { resolve, reject };\n if (signal) {\n const onAbort = () => {\n this.pending.delete(id);\n reject(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n pending.removeAbort = () => signal.removeEventListener(\"abort\", onAbort);\n }\n this.pending.set(id, pending);\n this.worker.postMessage({ type: \"render\", id, html, page, metadata, cssProfile, marginBoxes, pageRules });\n });\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.worker.terminate();\n for (const pending of this.pending.values()) {\n pending.removeAbort?.();\n pending.reject(new Error(\"Renderer was disposed\"));\n }\n this.pending.clear();\n }\n\n private handleMessage(event: MessageEvent): void {\n const message = event.data;\n if (message?.type !== \"render-result\" && message?.type !== \"render-error\") return;\n const pending = this.pending.get(message.id);\n if (!pending) return;\n this.pending.delete(message.id);\n pending.removeAbort?.();\n\n if (message.type === \"render-error\") {\n pending.reject(new WasmRenderError(message.error, -21));\n } else {\n pending.resolve({\n bytes: new Uint8Array(message.bytes),\n pageCount: message.pageCount,\n diagnostics: Array.isArray(message.diagnostics) ? message.diagnostics : [],\n });\n }\n }\n}\n\n/**\n * Reusable renderer backed by one Worker or main-thread WASM context.\n *\n * @remarks\n * Create instances with `createRenderer`. Fonts and execution mode belong to\n * the renderer lifetime; each returned `PdfDocument` has its own shorter\n * lifetime. Call `dispose` when the renderer is no longer needed.\n */\nexport class Html2RealPdf {\n private disposed = false;\n\n private constructor(private readonly backend: Backend) {}\n\n /** @internal */\n static create(backend: Backend): Html2RealPdf {\n return new Html2RealPdf(backend);\n }\n\n /**\n * Snapshots browser state and renders one PDF.\n *\n * @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.\n * @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.\n * @throws {@link ResourceLoadError} when required resources cannot be materialized.\n */\n async render(source: HtmlSource, options: RenderOptions = {}): Promise<PdfDocument> {\n if (this.disposed) throw new Error(\"Renderer has been disposed\");\n if (options.signal?.aborted) throw abortReason(options.signal);\n options.onProgress?.({ phase: \"snapshot\", completed: 0, total: 1 });\n const snapshotOptions: SnapshotOptions = {\n resourcePolicy: options.resourcePolicy ?? \"error\",\n cssProfile: options.cssProfile ?? \"document\",\n // Preserve the historical browser snapshot behavior unless callers\n // explicitly request print media. The web-profile example in the public\n // API opts into print rather than silently changing existing documents.\n mediaType: options.mediaType ?? \"screen\",\n unsupportedCss: options.unsupportedCss ?? (options.cssProfile === \"strict\" || options.strict ? \"error\" : \"warn\"),\n // Raster fallback is deliberately opt-in. A caller must acknowledge the\n // loss of native PDF primitives for the affected subtree explicitly.\n fallback: options.fallback ?? \"error\",\n };\n if (options.baseUrl !== undefined) snapshotOptions.baseUrl = options.baseUrl;\n if (options.resourceResolver !== undefined) snapshotOptions.resourceResolver = options.resourceResolver;\n if (options.strict !== undefined) snapshotOptions.strict = options.strict;\n if (options.enableLinks !== undefined) snapshotOptions.enableLinks = options.enableLinks;\n if (options.layoutContext !== undefined) snapshotOptions.layoutContext = options.layoutContext;\n if (options.viewport !== undefined) snapshotOptions.viewport = options.viewport;\n if (options.includeShadowDom !== undefined) snapshotOptions.includeShadowDom = options.includeShadowDom;\n if (options.canvasToSvg !== undefined) snapshotOptions.canvasToSvg = options.canvasToSvg;\n if (options.canvasFallback !== undefined) snapshotOptions.canvasFallback = options.canvasFallback;\n const snapshot = await snapshotSource(source, snapshotOptions);\n if (options.signal?.aborted) throw abortReason(options.signal);\n options.onProgress?.({ phase: \"snapshot\", completed: 1, total: 1 });\n\n options.onProgress?.({ phase: \"wasm\", completed: 0, total: 1 });\n const page = options.page !== undefined ? normalizePage(options.page) : snapshot.page ?? normalizePage();\n const rendered = await this.backend.render(\n applyPageBreakRules(snapshot.html, options.pageBreak),\n page,\n options.metadata,\n options.cssProfile ?? \"document\",\n snapshot.pageMarginBoxes,\n options.page === undefined ? snapshot.pageRules : undefined,\n options.signal,\n );\n options.onProgress?.({ phase: \"wasm\", completed: 1, total: 1 });\n options.onProgress?.({ phase: \"complete\", completed: 1, total: 1 });\n return PdfDocument.create(rendered.bytes, rendered.pageCount, [...snapshot.diagnostics, ...rendered.diagnostics]);\n }\n\n /** Terminates the owned backend and rejects future renders. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.backend.dispose();\n }\n}\n\n/**\n * Creates a reusable renderer with explicit backend and font ownership.\n *\n * @example\n * ```ts\n * const renderer = await createRenderer({ fonts });\n * try {\n * const pdf = await renderer.render(element);\n * try { pdf.download(\"report.pdf\"); } finally { pdf.dispose(); }\n * } finally {\n * renderer.dispose();\n * }\n * ```\n *\n * @throws {@link UnsupportedEnvironmentError} outside a browser or when the\n * requested execution backend is unavailable.\n */\nexport async function createRenderer(init: RendererInit = {}): Promise<Html2RealPdf> {\n if (typeof window === \"undefined\") throw new UnsupportedEnvironmentError();\n if (init.execution !== \"main\" && typeof Worker === \"undefined\") {\n throw new UnsupportedEnvironmentError(\"html2realpdf Worker execution is unavailable; use execution: 'main' as a fallback\");\n }\n const wasmUrl = new URL(init.wasmUrl ?? new URL(\"./libhtml2realpdf.wasm\", import.meta.url), window.location.href).href;\n const backend: Backend = init.execution === \"main\"\n ? new MainThreadBackend(await WasmBridge.create(wasmUrl, init.fonts ?? []))\n : new WorkerBackend(wasmUrl, init.fonts ?? []);\n return Html2RealPdf.create(backend);\n}\n\nlet defaultRenderer: Promise<Html2RealPdf> | undefined;\n\n/**\n * Renders with a lazily created package-default Worker renderer.\n *\n * @remarks\n * The default renderer is cached for the application lifetime and cannot be\n * configured with custom fonts. Use `createRenderer` when deterministic\n * backend disposal or renderer-level configuration is required. The returned\n * document must still be disposed by the caller.\n *\n * @example\n * ```ts\n * const pdf = await renderPdf(document.querySelector(\"#invoice\")!);\n * try { pdf.download(\"invoice.pdf\"); } finally { pdf.dispose(); }\n * ```\n */\nexport async function renderPdf(source: HtmlSource, options: RenderOptions = {}): Promise<PdfDocument> {\n defaultRenderer ??= createRenderer().catch((error: unknown) => {\n defaultRenderer = undefined;\n throw error;\n });\n return (await defaultRenderer).render(source, options);\n}\n\nfunction applyPageBreakRules(html: string, rules?: PageBreakRules): string {\n if (!rules) return html;\n const declarations: string[] = [];\n // DOM snapshots carry computed break properties as inline declarations.\n // Option-driven rules therefore need author importance to override the\n // snapshot's inline `auto` value while still yielding to inline !important.\n appendSelectorRule(declarations, rules.before, \"break-before:page!important\");\n appendSelectorRule(declarations, rules.after, \"break-after:page!important\");\n appendSelectorRule(declarations, rules.avoid, \"break-inside:avoid!important\");\n if (rules.legacy) declarations.push(\".html2pdf__page-break{break-before:page!important}\");\n if (rules.avoidAll) declarations.push(\"body *{break-inside:avoid!important}\");\n return declarations.length === 0 ? html : `<style data-html2realpdf-pagebreak>${declarations.join(\"\")}</style>${html}`;\n}\n\nfunction appendSelectorRule(output: string[], input: string | readonly string[] | undefined, declaration: string): void {\n const selectors = typeof input === \"string\" ? [input] : input ?? [];\n const safe = selectors.map((selector) => selector.trim()).filter((selector) => selector && !/[{};]/.test(selector));\n if (safe.length > 0) output.push(`${safe.join(\",\")}{${declaration}}`);\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"renderer.js","sourceRoot":"","sources":["../src/renderer.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,2BAA2B,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC3E,OAAO,EAAE,aAAa,EAAuB,MAAM,WAAW,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,cAAc,EAA2E,MAAM,eAAe,CAAC;AAExH,OAAO,EAAE,gBAAgB,EAAkB,MAAM,kBAAkB,CAAC;AACpE,OAAO,EAAE,UAAU,EAAyB,MAAM,WAAW,CAAC;AAQ9D,sEAAsE;AACtE,MAAM,iBAAiB;IACQ,MAAM;IAAnC,YAA6B,MAAkB;sBAAlB,MAAM;IAAe,CAAC;IAEnD,MAAM,CAAC,IAAY,EAAE,IAAoB,EAAE,QAAsB,EAAE,UAAuB,EAAE,WAA8C,EAAE,SAAuC,EAAE,MAAoB,EAAE,MAAkB;QAC3N,IAAI,MAAM,EAAE,OAAO;YAAE,OAAO,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC;QAChE,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,UAAU,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;IAC/G,CAAC;IAED,OAAO;QACL,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;CACF;AASD,gFAAgF;AAChF,MAAM,aAAa;IACA,MAAM,CAAS;IACf,OAAO,GAAG,IAAI,GAAG,EAAyB,CAAC;IAC3C,KAAK,CAAgB;IAC9B,MAAM,GAAG,CAAC,CAAC;IACX,QAA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AAC,IAAI,WAAW,GAAG,CAAC,CAAC;AACxE,CAAC;AAED,SAAS,WAAW,CAAC,MAAmB;IACtC,OAAO,MAAM,CAAC,MAAM,IAAI,IAAI,YAAY,CAAC,2BAA2B,EAAE,YAAY,CAAC,CAAC;AACtF,CAAC","sourcesContent":["/**\n * Renderer factories, execution backends, and per-render pipeline ownership.\n *\n * @packageDocumentation\n */\n\nimport { UnsupportedEnvironmentError, WasmRenderError } from \"./errors.js\";\nimport { normalizePage, type NormalizedPage } from \"./page.js\";\nimport { PdfDocument } from \"./pdf-document.js\";\nimport { snapshotSource, type SnapshotOptions, type SnapshotPageMarginBox, type SnapshotPageRule } from \"./snapshot.js\";\nimport type { CssProfile, FontRegistration, HtmlSource, PageBreakRules, PdfMetadata, RendererInit, RenderOptions } from \"./types.js\";\nimport { preparePdfExtras, type PdfExtras } from \"./attachments.js\";\nimport { WasmBridge, type WasmRenderResult } from \"./wasm.js\";\n\n/** Common ownership boundary for main-thread and Worker WASM contexts. */\ninterface Backend {\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult>;\n dispose(): void;\n}\n\n/** Executes the synchronous bridge on the caller's browser thread. */\nclass MainThreadBackend implements Backend {\n constructor(private readonly bridge: WasmBridge) {}\n\n render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult> {\n if (signal?.aborted) return Promise.reject(abortReason(signal));\n return Promise.resolve(this.bridge.render(html, page, metadata, cssProfile, marginBoxes, pageRules, extras));\n }\n\n dispose(): void {\n this.bridge.dispose();\n }\n}\n\n/** Caller state retained while a Worker render is in flight. */\ninterface PendingRender {\n resolve: (result: WasmRenderResult) => void;\n reject: (error: unknown) => void;\n removeAbort?: () => void;\n}\n\n/** Owns a module Worker and routes concurrent results by request identifier. */\nclass WorkerBackend implements Backend {\n private readonly worker: Worker;\n private readonly pending = new Map<number, PendingRender>();\n private readonly ready: Promise<void>;\n private nextId = 1;\n private disposed = false;\n\n constructor(wasmUrl: string, fonts: readonly FontRegistration[]) {\n this.worker = new Worker(new URL(\"./worker.js\", import.meta.url), { type: \"module\", name: \"html2realpdf\" });\n this.ready = new Promise<void>((resolve, reject) => {\n const onError = (event: ErrorEvent) => {\n this.worker.removeEventListener(\"message\", onMessage);\n reject(new WasmRenderError(event.message || \"PDF Worker initialization failed\", -20));\n };\n const onMessage = (event: MessageEvent) => {\n if (event.data?.type === \"ready\") {\n this.worker.removeEventListener(\"message\", onMessage);\n this.worker.removeEventListener(\"error\", onError);\n resolve();\n } else if (event.data?.type === \"init-error\") {\n this.worker.removeEventListener(\"message\", onMessage);\n this.worker.removeEventListener(\"error\", onError);\n reject(new WasmRenderError(event.data.error, -20));\n }\n };\n this.worker.addEventListener(\"message\", onMessage);\n this.worker.addEventListener(\"error\", onError, { once: true });\n });\n this.worker.addEventListener(\"message\", (event) => this.handleMessage(event));\n this.worker.addEventListener(\"error\", (event) => {\n const error = new WasmRenderError(event.message || \"PDF Worker failed\", -22);\n for (const pending of this.pending.values()) {\n pending.removeAbort?.();\n pending.reject(error);\n }\n this.pending.clear();\n });\n this.worker.postMessage({ type: \"init\", wasmUrl, fonts });\n }\n\n async render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], signal?: AbortSignal, extras?: PdfExtras): Promise<WasmRenderResult> {\n if (this.disposed) throw new Error(\"Renderer has been disposed\");\n if (signal?.aborted) throw abortReason(signal);\n await this.ready;\n\n const id = this.nextId++;\n return new Promise<WasmRenderResult>((resolve, reject) => {\n const pending: PendingRender = { resolve, reject };\n if (signal) {\n const onAbort = () => {\n this.pending.delete(id);\n reject(abortReason(signal));\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n pending.removeAbort = () => signal.removeEventListener(\"abort\", onAbort);\n }\n this.pending.set(id, pending);\n try {\n this.worker.postMessage({ type: \"render\", id, html, page, metadata, cssProfile, marginBoxes, pageRules, extras },\n extras?.attachments?.map((attachment) => attachment.data.buffer) ?? []);\n } catch (error) {\n this.pending.delete(id);\n pending.removeAbort?.();\n reject(error);\n }\n });\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.worker.terminate();\n for (const pending of this.pending.values()) {\n pending.removeAbort?.();\n pending.reject(new Error(\"Renderer was disposed\"));\n }\n this.pending.clear();\n }\n\n private handleMessage(event: MessageEvent): void {\n const message = event.data;\n if (message?.type !== \"render-result\" && message?.type !== \"render-error\") return;\n const pending = this.pending.get(message.id);\n if (!pending) return;\n this.pending.delete(message.id);\n pending.removeAbort?.();\n\n if (message.type === \"render-error\") {\n pending.reject(new WasmRenderError(message.error, -21));\n } else {\n pending.resolve({\n bytes: new Uint8Array(message.bytes),\n pageCount: message.pageCount,\n diagnostics: Array.isArray(message.diagnostics) ? message.diagnostics : [],\n });\n }\n }\n}\n\n/**\n * Reusable renderer backed by one Worker or main-thread WASM context.\n *\n * @remarks\n * Create instances with `createRenderer`. Fonts and execution mode belong to\n * the renderer lifetime; each returned `PdfDocument` has its own shorter\n * lifetime. Call `dispose` when the renderer is no longer needed.\n */\nexport class Html2RealPdf {\n private disposed = false;\n\n private constructor(private readonly backend: Backend) {}\n\n /** @internal */\n static create(backend: Backend): Html2RealPdf {\n return new Html2RealPdf(backend);\n }\n\n /**\n * Snapshots browser state and renders one PDF.\n *\n * @throws {@link InvalidSourceError} when a ref is null or the source shape is invalid.\n * @throws {@link UnsupportedCssError} when strict CSS or fallback policy rejects input.\n * @throws {@link ResourceLoadError} when required resources cannot be materialized.\n */\n async render(source: HtmlSource, options: RenderOptions = {}): Promise<PdfDocument> {\n if (this.disposed) throw new Error(\"Renderer has been disposed\");\n if (options.signal?.aborted) throw abortReason(options.signal);\n const extras = preparePdfExtras(options);\n options.onProgress?.({ phase: \"snapshot\", completed: 0, total: 1 });\n const snapshotOptions: SnapshotOptions = {\n resourcePolicy: options.resourcePolicy ?? \"error\",\n cssProfile: options.cssProfile ?? \"document\",\n // Preserve the historical browser snapshot behavior unless callers\n // explicitly request print media. The web-profile example in the public\n // API opts into print rather than silently changing existing documents.\n mediaType: options.mediaType ?? \"screen\",\n unsupportedCss: options.unsupportedCss ?? (options.cssProfile === \"strict\" || options.strict ? \"error\" : \"warn\"),\n // Raster fallback is deliberately opt-in. A caller must acknowledge the\n // loss of native PDF primitives for the affected subtree explicitly.\n fallback: options.fallback ?? \"error\",\n };\n if (options.baseUrl !== undefined) snapshotOptions.baseUrl = options.baseUrl;\n if (options.resourceResolver !== undefined) snapshotOptions.resourceResolver = options.resourceResolver;\n if (options.strict !== undefined) snapshotOptions.strict = options.strict;\n if (options.enableLinks !== undefined) snapshotOptions.enableLinks = options.enableLinks;\n if (options.layoutContext !== undefined) snapshotOptions.layoutContext = options.layoutContext;\n if (options.viewport !== undefined) snapshotOptions.viewport = options.viewport;\n if (options.includeShadowDom !== undefined) snapshotOptions.includeShadowDom = options.includeShadowDom;\n if (options.canvasToSvg !== undefined) snapshotOptions.canvasToSvg = options.canvasToSvg;\n if (options.canvasFallback !== undefined) snapshotOptions.canvasFallback = options.canvasFallback;\n const snapshot = await snapshotSource(source, snapshotOptions);\n if (options.signal?.aborted) throw abortReason(options.signal);\n options.onProgress?.({ phase: \"snapshot\", completed: 1, total: 1 });\n\n options.onProgress?.({ phase: \"wasm\", completed: 0, total: 1 });\n const page = options.page !== undefined ? normalizePage(options.page) : snapshot.page ?? normalizePage();\n const rendered = await this.backend.render(\n applyPageBreakRules(snapshot.html, options.pageBreak),\n page,\n options.metadata,\n options.cssProfile ?? \"document\",\n snapshot.pageMarginBoxes,\n options.page === undefined ? snapshot.pageRules : undefined,\n options.signal,\n extras,\n );\n options.onProgress?.({ phase: \"wasm\", completed: 1, total: 1 });\n options.onProgress?.({ phase: \"complete\", completed: 1, total: 1 });\n return PdfDocument.create(rendered.bytes, rendered.pageCount, [...snapshot.diagnostics, ...rendered.diagnostics]);\n }\n\n /** Terminates the owned backend and rejects future renders. */\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.backend.dispose();\n }\n}\n\n/**\n * Creates a reusable renderer with explicit backend and font ownership.\n *\n * @example\n * ```ts\n * const renderer = await createRenderer({ fonts });\n * try {\n * const pdf = await renderer.render(element);\n * try { pdf.download(\"report.pdf\"); } finally { pdf.dispose(); }\n * } finally {\n * renderer.dispose();\n * }\n * ```\n *\n * @throws {@link UnsupportedEnvironmentError} outside a browser or when the\n * requested execution backend is unavailable.\n */\nexport async function createRenderer(init: RendererInit = {}): Promise<Html2RealPdf> {\n if (typeof window === \"undefined\") throw new UnsupportedEnvironmentError();\n if (init.execution !== \"main\" && typeof Worker === \"undefined\") {\n throw new UnsupportedEnvironmentError(\"html2realpdf Worker execution is unavailable; use execution: 'main' as a fallback\");\n }\n const wasmUrl = new URL(init.wasmUrl ?? new URL(\"./libhtml2realpdf.wasm\", import.meta.url), window.location.href).href;\n const backend: Backend = init.execution === \"main\"\n ? new MainThreadBackend(await WasmBridge.create(wasmUrl, init.fonts ?? []))\n : new WorkerBackend(wasmUrl, init.fonts ?? []);\n return Html2RealPdf.create(backend);\n}\n\nlet defaultRenderer: Promise<Html2RealPdf> | undefined;\n\n/**\n * Renders with a lazily created package-default Worker renderer.\n *\n * @remarks\n * The default renderer is cached for the application lifetime and cannot be\n * configured with custom fonts. Use `createRenderer` when deterministic\n * backend disposal or renderer-level configuration is required. The returned\n * document must still be disposed by the caller.\n *\n * @example\n * ```ts\n * const pdf = await renderPdf(document.querySelector(\"#invoice\")!);\n * try { pdf.download(\"invoice.pdf\"); } finally { pdf.dispose(); }\n * ```\n */\nexport async function renderPdf(source: HtmlSource, options: RenderOptions = {}): Promise<PdfDocument> {\n defaultRenderer ??= createRenderer().catch((error: unknown) => {\n defaultRenderer = undefined;\n throw error;\n });\n return (await defaultRenderer).render(source, options);\n}\n\nfunction applyPageBreakRules(html: string, rules?: PageBreakRules): string {\n if (!rules) return html;\n const declarations: string[] = [];\n // DOM snapshots carry computed break properties as inline declarations.\n // Option-driven rules therefore need author importance to override the\n // snapshot's inline `auto` value while still yielding to inline !important.\n appendSelectorRule(declarations, rules.before, \"break-before:page!important\");\n appendSelectorRule(declarations, rules.after, \"break-after:page!important\");\n appendSelectorRule(declarations, rules.avoid, \"break-inside:avoid!important\");\n if (rules.legacy) declarations.push(\".html2pdf__page-break{break-before:page!important}\");\n if (rules.avoidAll) declarations.push(\"body *{break-inside:avoid!important}\");\n return declarations.length === 0 ? html : `<style data-html2realpdf-pagebreak>${declarations.join(\"\")}</style>${html}`;\n}\n\nfunction appendSelectorRule(output: string[], input: string | readonly string[] | undefined, declaration: string): void {\n const selectors = typeof input === \"string\" ? [input] : input ?? [];\n const safe = selectors.map((selector) => selector.trim()).filter((selector) => selector && !/[{};]/.test(selector));\n if (safe.length > 0) output.push(`${safe.join(\",\")}{${declaration}}`);\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -202,6 +202,10 @@ export interface RenderOptions {
|
|
|
202
202
|
pageBreak?: PageBreakRules;
|
|
203
203
|
/** PDF information dictionary fields. */
|
|
204
204
|
metadata?: PdfMetadata;
|
|
205
|
+
/** Opts into PDF/A-3u; incompatible resources reject the render without fallback. */
|
|
206
|
+
conformance?: "pdfa-3u";
|
|
207
|
+
/** Embedded files for this render only; does not implicitly enable PDF/A. */
|
|
208
|
+
attachments?: readonly PdfAttachment[];
|
|
205
209
|
/** Preserves HTTP(S), mail, telephone, and FTP annotations unless explicitly set to `false`. */
|
|
206
210
|
enableLinks?: boolean;
|
|
207
211
|
/**
|
|
@@ -254,6 +258,10 @@ export interface CompatPageBreakOptions {
|
|
|
254
258
|
}
|
|
255
259
|
/** Options supported by the PDF-oriented html2pdf.js compatibility layer. */
|
|
256
260
|
export interface Html2PdfOptions {
|
|
261
|
+
/** Same metadata and archival options as RenderOptions. */
|
|
262
|
+
metadata?: PdfMetadata;
|
|
263
|
+
conformance?: "pdfa-3u";
|
|
264
|
+
attachments?: readonly PdfAttachment[];
|
|
257
265
|
/** Page margins in html2pdf.js order. */
|
|
258
266
|
margin?: Margin;
|
|
259
267
|
/** Filename used by `save` when no method argument is supplied. */
|
|
@@ -271,3 +279,18 @@ export interface Html2PdfOptions {
|
|
|
271
279
|
}
|
|
272
280
|
/** Output encodings supported by compatibility `output` methods. */
|
|
273
281
|
export type PdfOutputType = "arraybuffer" | "blob" | "bloburl" | "bloburi" | "datauristring" | "dataurlstring";
|
|
282
|
+
/** File embedded in one PDF; caller data is copied and never transferred or detached. */
|
|
283
|
+
export interface PdfAttachment {
|
|
284
|
+
/** Nonempty, unique filename. Unicode is preserved. */
|
|
285
|
+
name: string;
|
|
286
|
+
/** Original bytes; a Uint8Array embeds only its selected view. */
|
|
287
|
+
data: ArrayBuffer | Uint8Array;
|
|
288
|
+
/** MIME media type without parameters. Defaults to application/octet-stream. */
|
|
289
|
+
mimeType?: string;
|
|
290
|
+
/** Relationship to the document. Defaults to Unspecified. */
|
|
291
|
+
relationship?: "Source" | "Data" | "Alternative" | "Supplement" | "Unspecified";
|
|
292
|
+
/** Optional human-readable attachment description. */
|
|
293
|
+
description?: string;
|
|
294
|
+
/** Explicit modification time, stored in UTC with second precision; no date is invented. */
|
|
295
|
+
modifiedAt?: Date;
|
|
296
|
+
}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG","sourcesContent":["/**\n * Public configuration and callback contracts for the browser wrapper.\n *\n * @packageDocumentation\n */\n\n/** A structural ref accepted without making React a runtime dependency. */\nexport type RefLike<T> = { readonly current: T | null };\n\n/**\n * Input accepted by the snapshot boundary.\n *\n * @remarks\n * Mounted elements and refs preserve computed styles and live browser state;\n * strings are evaluated in an inert document.\n */\nexport type HtmlSource = string | Element | RefLike<Element>;\n\n/** Units used for custom page dimensions and margins. */\nexport type LengthUnit = \"pt\" | \"px\" | \"mm\" | \"cm\" | \"in\";\n\n/** Named physical page sizes or a custom `[width, height]` in the selected unit. */\nexport type PageFormat = \"a4\" | \"letter\" | readonly [width: number, height: number];\n\n/** Orientation applied after resolving the page format. */\nexport type PageOrientation = \"portrait\" | \"landscape\";\n\n/**\n * Layout and CSS support profile.\n *\n * @remarks\n * `document` favors stable paged reports. `web` enables the broader browser\n * layout profile. `strict` uses that broader profile and rejects unsupported\n * CSS by default.\n */\nexport type CssProfile = \"document\" | \"web\" | \"strict\";\n\n/** Media environment used while resolving styles and media queries. */\nexport type MediaType = \"screen\" | \"print\";\n\n/** Containing block used for the snapshotted root element. */\nexport type LayoutContext = \"source\" | \"page\";\n\n/** Action taken when an authored CSS property is outside the selected profile. */\nexport type UnsupportedCssPolicy = \"warn\" | \"error\" | \"ignore\";\n\n/** Policy for SVG subtrees that cannot remain native PDF vectors. */\nexport type FallbackPolicy = \"error\" | \"rasterize-subtree\";\n\n/** Policy used when a canvas-to-SVG adapter intentionally returns `null`. */\nexport type CanvasFallbackPolicy = \"error\" | \"rasterize\";\n\n/** Complete SVG returned by a canvas adapter. */\nexport type CanvasSvgSource = string | Blob | SVGSVGElement;\n\n/** Context passed to a canvas-to-SVG adapter. */\nexport interface CanvasToSvgRequest {\n /** Original live canvas, suitable for chart-library export APIs. */\n canvas: HTMLCanvasElement;\n /** Stable snapshot path used to identify failures and fallbacks. */\n nodePath: string;\n /** Rendered canvas width in CSS pixels. */\n cssWidth: number;\n /** Rendered canvas height in CSS pixels. */\n cssHeight: number;\n /** Backing bitmap width. */\n bitmapWidth: number;\n /** Backing bitmap height. */\n bitmapHeight: number;\n}\n\n/**\n * Replaces a live canvas with vector SVG when the source library can export it.\n *\n * @remarks\n * Returning `null` delegates to `canvasFallback`. Throwing or returning\n * malformed SVG produces `CanvasToSvgError`.\n */\nexport type CanvasToSvg = (\n request: CanvasToSvgRequest,\n) => CanvasSvgSource | null | Promise<CanvasSvgSource | null>;\n\n/** Deterministic viewport used for responsive layout and media queries. */\nexport interface ViewportOptions {\n /** Viewport width in CSS pixels. Values below one are clamped. */\n width: number;\n /** Viewport height in CSS pixels. Values below one are clamped. */\n height: number;\n}\n\n/**\n * Page margins in the selected page unit.\n *\n * @remarks\n * Four values use html2pdf.js order `[top, left, bottom, right]`, not CSS\n * shorthand order. Two values mean `[vertical, horizontal]`.\n */\nexport type Margin =\n | number\n | readonly [vertical: number, horizontal: number]\n | readonly [top: number, left: number, bottom: number, right: number];\n\n/** Explicit page geometry. Supplying this overrides captured `@page` geometry. */\nexport interface PageOptions {\n /** Page size. Defaults to `a4`. */\n format?: PageFormat;\n /** Page orientation. Defaults to `portrait`. */\n orientation?: PageOrientation;\n /** Unit for custom dimensions and margins. Defaults to `pt`. */\n unit?: LengthUnit;\n /** Page margins. Defaults to zero on every edge. */\n margin?: Margin;\n}\n\n/** Coarse rendering phases reported at stable cancellation boundaries. */\nexport type RenderPhase = \"snapshot\" | \"wasm\" | \"complete\";\n\n/** Progress notification for a rendering phase. */\nexport interface RenderProgress {\n /** Phase producing this notification. */\n phase: RenderPhase;\n /** Completed work units within the phase. */\n completed: number;\n /** Total work units within the phase. */\n total: number;\n}\n\n/** Structured warning or error produced without losing successful PDF output. */\nexport interface Diagnostic {\n /** Stable machine-readable identifier. */\n code: string;\n /** Diagnostic severity assigned by the snapshot or native renderer. */\n severity: \"warning\" | \"error\";\n /** Human-readable explanation. */\n message: string;\n /** CSS property associated with the diagnostic, when applicable. */\n property?: string;\n /** Stable snapshot path to the affected node, when available. */\n nodePath?: string;\n /** Pipeline phase that produced the diagnostic. */\n phase?: \"snapshot\" | \"parse\" | \"cascade\" | \"computed\" | \"layout\" | \"fragmentation\" | \"paint\" | \"pdf\";\n /** Fallback that preserved output despite the unsupported input. */\n fallback?: string;\n}\n\n/** Resource requested while materializing a self-contained snapshot. */\nexport interface ResourceRequest {\n /** Resource class. Fonts are registered on `createRenderer` instead. */\n kind: \"image\" | \"stylesheet\";\n /** Absolute URL resolved against `baseUrl` or the source document. */\n url: URL;\n}\n\n/**\n * Resolves resources that cannot be fetched directly by the browser snapshot.\n *\n * @remarks\n * For stylesheets, a string is CSS source. For images, a string is a data URL\n * or replacement URL. `null` leaves the request unresolved and applies\n * `resourcePolicy`.\n */\nexport type ResourceResolver = (request: ResourceRequest) => Blob | string | null | Promise<Blob | string | null>;\n\n/** Selector-driven pagination overrides compatible with html2pdf.js workflows. */\nexport interface PageBreakRules {\n /** Selectors forced to begin on a new page. */\n before?: string | readonly string[];\n /** Selectors forced to end the current page. */\n after?: string | readonly string[];\n /** Selectors whose contents should avoid internal fragmentation. */\n avoid?: string | readonly string[];\n /** Applies `break-inside: avoid` to every element. */\n avoidAll?: boolean;\n /** Honors the legacy `.html2pdf__page-break` marker. */\n legacy?: boolean;\n}\n\n/** PDF information dictionary fields written by the native renderer. */\nexport interface PdfMetadata {\n /** Document title. */\n title?: string;\n /** Document author. */\n author?: string;\n /** Document subject. */\n subject?: string;\n /** Search keywords, joined when supplied as an array. */\n keywords?: string | readonly string[];\n /** Application or service that created the document. */\n creator?: string;\n}\n\n/** Options applied to one HTML snapshot and PDF render. */\nexport interface RenderOptions {\n /** Explicit page geometry; captured `@page` rules are used when omitted. */\n page?: PageOptions;\n /**\n * Promotes unsupported snapshot CSS to errors without selecting the `web`\n * layout profile. An explicit `unsupportedCss` policy takes precedence.\n */\n strict?: boolean;\n /** Layout profile. Defaults to `document`. */\n cssProfile?: CssProfile;\n /** Media environment used for style resolution. Defaults to `screen`. */\n mediaType?: MediaType;\n /**\n * Root layout context. `source` preserves the mounted browser width;\n * `page` resolves an implicit root width and auto inline margins against the\n * PDF content box. Defaults to `source`.\n */\n layoutContext?: LayoutContext;\n /** Isolated viewport used for media queries and responsive layout. */\n viewport?: ViewportOptions;\n /** Unsupported-CSS policy; defaults to `error` for strict mode and `warn` otherwise. */\n unsupportedCss?: UnsupportedCssPolicy;\n /** Unsupported SVG policy. Defaults to `error`. */\n fallback?: FallbackPolicy;\n /** Optional bridge from live canvas content to validated SVG. */\n canvasToSvg?: CanvasToSvg;\n /** Fallback when `canvasToSvg` returns `null`. Defaults to `error`. */\n canvasFallback?: CanvasFallbackPolicy;\n /** Flattens open Shadow DOM into the snapshot. Defaults to `false`. */\n includeShadowDom?: boolean;\n /** Base URL for relative resources. Defaults to the source document URL. */\n baseUrl?: string | URL;\n /** Failed-resource policy. Defaults to `error`. */\n resourcePolicy?: \"error\" | \"omit\";\n /** Resolver for protected, virtual, or otherwise unavailable resources. */\n resourceResolver?: ResourceResolver;\n /** Selector-driven page-break overrides. */\n pageBreak?: PageBreakRules;\n /** PDF information dictionary fields. */\n metadata?: PdfMetadata;\n /** Preserves HTTP(S), mail, telephone, and FTP annotations unless explicitly set to `false`. */\n enableLinks?: boolean;\n /**\n * Rejects the caller at snapshot and render boundaries when aborted.\n * An already-running synchronous WASM render cannot be preempted.\n */\n signal?: AbortSignal;\n /** Receives coarse phase-boundary progress, not per-page render progress. */\n onProgress?: (progress: RenderProgress) => void;\n}\n\n/** Configuration whose lifetime matches an explicit renderer instance. */\nexport interface RendererInit {\n /** Execution backend. Defaults to `worker`. */\n execution?: \"worker\" | \"main\";\n /** WASM asset override for deployments that cannot serve package-relative assets. */\n wasmUrl?: string | URL;\n /** Embeddable TrueType fonts registered once for every render. */\n fonts?: readonly FontRegistration[];\n}\n\n/** Embeddable TrueType font registered in a renderer-owned WASM context. */\nexport interface FontRegistration {\n /** CSS family name used during font resolution. */\n family: string;\n /** Complete TrueType font bytes, copied into the native context. */\n data: ArrayBuffer | Uint8Array;\n /** CSS font weight. Defaults to `400`. */\n weight?: number | \"normal\" | \"bold\";\n /** CSS font style. Defaults to `normal`. */\n style?: \"normal\" | \"italic\";\n}\n\n/** Page settings accepted through the html2pdf.js-compatible `jsPDF` option. */\nexport interface CompatJsPdfOptions {\n /** Unit shared by custom page geometry and margins. */\n unit?: LengthUnit;\n /** Named or custom page format forwarded to the modern page contract. */\n format?: PageFormat;\n /** Page orientation forwarded to the modern page contract. */\n orientation?: PageOrientation;\n}\n\n/** Page-break settings accepted by the html2pdf.js compatibility layer. */\nexport interface CompatPageBreakOptions {\n /** Compatibility modes. Defaults to `css` and `legacy`. */\n mode?: \"css\" | \"legacy\" | \"avoid-all\" | readonly (\"css\" | \"legacy\" | \"avoid-all\")[];\n /** Selectors forced to begin on a new page. */\n before?: string | readonly string[];\n /** Selectors forced to end the current page. */\n after?: string | readonly string[];\n /** Selectors whose contents should avoid internal fragmentation. */\n avoid?: string | readonly string[];\n}\n\n/** Options supported by the PDF-oriented html2pdf.js compatibility layer. */\nexport interface Html2PdfOptions {\n /** Page margins in html2pdf.js order. */\n margin?: Margin;\n /** Filename used by `save` when no method argument is supplied. */\n filename?: string;\n /** Preserves HTTP(S), mail, telephone, and FTP links unless explicitly disabled. */\n enableLinks?: boolean;\n /** Compatibility pagination rules. */\n pagebreak?: CompatPageBreakOptions;\n /** Compatibility page geometry. */\n jsPDF?: CompatJsPdfOptions;\n /** Unsupported because this renderer does not use an html2canvas pipeline. */\n html2canvas?: never;\n /** Unsupported because PDF pages are not encoded as raster images. */\n image?: never;\n}\n\n/** Output encodings supported by compatibility `output` methods. */\nexport type PdfOutputType =\n | \"arraybuffer\"\n | \"blob\"\n | \"bloburl\"\n | \"bloburi\"\n | \"datauristring\"\n | \"dataurlstring\";\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG","sourcesContent":["/**\n * Public configuration and callback contracts for the browser wrapper.\n *\n * @packageDocumentation\n */\n\n/** A structural ref accepted without making React a runtime dependency. */\nexport type RefLike<T> = { readonly current: T | null };\n\n/**\n * Input accepted by the snapshot boundary.\n *\n * @remarks\n * Mounted elements and refs preserve computed styles and live browser state;\n * strings are evaluated in an inert document.\n */\nexport type HtmlSource = string | Element | RefLike<Element>;\n\n/** Units used for custom page dimensions and margins. */\nexport type LengthUnit = \"pt\" | \"px\" | \"mm\" | \"cm\" | \"in\";\n\n/** Named physical page sizes or a custom `[width, height]` in the selected unit. */\nexport type PageFormat = \"a4\" | \"letter\" | readonly [width: number, height: number];\n\n/** Orientation applied after resolving the page format. */\nexport type PageOrientation = \"portrait\" | \"landscape\";\n\n/**\n * Layout and CSS support profile.\n *\n * @remarks\n * `document` favors stable paged reports. `web` enables the broader browser\n * layout profile. `strict` uses that broader profile and rejects unsupported\n * CSS by default.\n */\nexport type CssProfile = \"document\" | \"web\" | \"strict\";\n\n/** Media environment used while resolving styles and media queries. */\nexport type MediaType = \"screen\" | \"print\";\n\n/** Containing block used for the snapshotted root element. */\nexport type LayoutContext = \"source\" | \"page\";\n\n/** Action taken when an authored CSS property is outside the selected profile. */\nexport type UnsupportedCssPolicy = \"warn\" | \"error\" | \"ignore\";\n\n/** Policy for SVG subtrees that cannot remain native PDF vectors. */\nexport type FallbackPolicy = \"error\" | \"rasterize-subtree\";\n\n/** Policy used when a canvas-to-SVG adapter intentionally returns `null`. */\nexport type CanvasFallbackPolicy = \"error\" | \"rasterize\";\n\n/** Complete SVG returned by a canvas adapter. */\nexport type CanvasSvgSource = string | Blob | SVGSVGElement;\n\n/** Context passed to a canvas-to-SVG adapter. */\nexport interface CanvasToSvgRequest {\n /** Original live canvas, suitable for chart-library export APIs. */\n canvas: HTMLCanvasElement;\n /** Stable snapshot path used to identify failures and fallbacks. */\n nodePath: string;\n /** Rendered canvas width in CSS pixels. */\n cssWidth: number;\n /** Rendered canvas height in CSS pixels. */\n cssHeight: number;\n /** Backing bitmap width. */\n bitmapWidth: number;\n /** Backing bitmap height. */\n bitmapHeight: number;\n}\n\n/**\n * Replaces a live canvas with vector SVG when the source library can export it.\n *\n * @remarks\n * Returning `null` delegates to `canvasFallback`. Throwing or returning\n * malformed SVG produces `CanvasToSvgError`.\n */\nexport type CanvasToSvg = (\n request: CanvasToSvgRequest,\n) => CanvasSvgSource | null | Promise<CanvasSvgSource | null>;\n\n/** Deterministic viewport used for responsive layout and media queries. */\nexport interface ViewportOptions {\n /** Viewport width in CSS pixels. Values below one are clamped. */\n width: number;\n /** Viewport height in CSS pixels. Values below one are clamped. */\n height: number;\n}\n\n/**\n * Page margins in the selected page unit.\n *\n * @remarks\n * Four values use html2pdf.js order `[top, left, bottom, right]`, not CSS\n * shorthand order. Two values mean `[vertical, horizontal]`.\n */\nexport type Margin =\n | number\n | readonly [vertical: number, horizontal: number]\n | readonly [top: number, left: number, bottom: number, right: number];\n\n/** Explicit page geometry. Supplying this overrides captured `@page` geometry. */\nexport interface PageOptions {\n /** Page size. Defaults to `a4`. */\n format?: PageFormat;\n /** Page orientation. Defaults to `portrait`. */\n orientation?: PageOrientation;\n /** Unit for custom dimensions and margins. Defaults to `pt`. */\n unit?: LengthUnit;\n /** Page margins. Defaults to zero on every edge. */\n margin?: Margin;\n}\n\n/** Coarse rendering phases reported at stable cancellation boundaries. */\nexport type RenderPhase = \"snapshot\" | \"wasm\" | \"complete\";\n\n/** Progress notification for a rendering phase. */\nexport interface RenderProgress {\n /** Phase producing this notification. */\n phase: RenderPhase;\n /** Completed work units within the phase. */\n completed: number;\n /** Total work units within the phase. */\n total: number;\n}\n\n/** Structured warning or error produced without losing successful PDF output. */\nexport interface Diagnostic {\n /** Stable machine-readable identifier. */\n code: string;\n /** Diagnostic severity assigned by the snapshot or native renderer. */\n severity: \"warning\" | \"error\";\n /** Human-readable explanation. */\n message: string;\n /** CSS property associated with the diagnostic, when applicable. */\n property?: string;\n /** Stable snapshot path to the affected node, when available. */\n nodePath?: string;\n /** Pipeline phase that produced the diagnostic. */\n phase?: \"snapshot\" | \"parse\" | \"cascade\" | \"computed\" | \"layout\" | \"fragmentation\" | \"paint\" | \"pdf\";\n /** Fallback that preserved output despite the unsupported input. */\n fallback?: string;\n}\n\n/** Resource requested while materializing a self-contained snapshot. */\nexport interface ResourceRequest {\n /** Resource class. Fonts are registered on `createRenderer` instead. */\n kind: \"image\" | \"stylesheet\";\n /** Absolute URL resolved against `baseUrl` or the source document. */\n url: URL;\n}\n\n/**\n * Resolves resources that cannot be fetched directly by the browser snapshot.\n *\n * @remarks\n * For stylesheets, a string is CSS source. For images, a string is a data URL\n * or replacement URL. `null` leaves the request unresolved and applies\n * `resourcePolicy`.\n */\nexport type ResourceResolver = (request: ResourceRequest) => Blob | string | null | Promise<Blob | string | null>;\n\n/** Selector-driven pagination overrides compatible with html2pdf.js workflows. */\nexport interface PageBreakRules {\n /** Selectors forced to begin on a new page. */\n before?: string | readonly string[];\n /** Selectors forced to end the current page. */\n after?: string | readonly string[];\n /** Selectors whose contents should avoid internal fragmentation. */\n avoid?: string | readonly string[];\n /** Applies `break-inside: avoid` to every element. */\n avoidAll?: boolean;\n /** Honors the legacy `.html2pdf__page-break` marker. */\n legacy?: boolean;\n}\n\n/** PDF information dictionary fields written by the native renderer. */\nexport interface PdfMetadata {\n /** Document title. */\n title?: string;\n /** Document author. */\n author?: string;\n /** Document subject. */\n subject?: string;\n /** Search keywords, joined when supplied as an array. */\n keywords?: string | readonly string[];\n /** Application or service that created the document. */\n creator?: string;\n}\n\n/** Options applied to one HTML snapshot and PDF render. */\nexport interface RenderOptions {\n /** Explicit page geometry; captured `@page` rules are used when omitted. */\n page?: PageOptions;\n /**\n * Promotes unsupported snapshot CSS to errors without selecting the `web`\n * layout profile. An explicit `unsupportedCss` policy takes precedence.\n */\n strict?: boolean;\n /** Layout profile. Defaults to `document`. */\n cssProfile?: CssProfile;\n /** Media environment used for style resolution. Defaults to `screen`. */\n mediaType?: MediaType;\n /**\n * Root layout context. `source` preserves the mounted browser width;\n * `page` resolves an implicit root width and auto inline margins against the\n * PDF content box. Defaults to `source`.\n */\n layoutContext?: LayoutContext;\n /** Isolated viewport used for media queries and responsive layout. */\n viewport?: ViewportOptions;\n /** Unsupported-CSS policy; defaults to `error` for strict mode and `warn` otherwise. */\n unsupportedCss?: UnsupportedCssPolicy;\n /** Unsupported SVG policy. Defaults to `error`. */\n fallback?: FallbackPolicy;\n /** Optional bridge from live canvas content to validated SVG. */\n canvasToSvg?: CanvasToSvg;\n /** Fallback when `canvasToSvg` returns `null`. Defaults to `error`. */\n canvasFallback?: CanvasFallbackPolicy;\n /** Flattens open Shadow DOM into the snapshot. Defaults to `false`. */\n includeShadowDom?: boolean;\n /** Base URL for relative resources. Defaults to the source document URL. */\n baseUrl?: string | URL;\n /** Failed-resource policy. Defaults to `error`. */\n resourcePolicy?: \"error\" | \"omit\";\n /** Resolver for protected, virtual, or otherwise unavailable resources. */\n resourceResolver?: ResourceResolver;\n /** Selector-driven page-break overrides. */\n pageBreak?: PageBreakRules;\n /** PDF information dictionary fields. */\n metadata?: PdfMetadata;\n /** Opts into PDF/A-3u; incompatible resources reject the render without fallback. */\n conformance?: \"pdfa-3u\";\n /** Embedded files for this render only; does not implicitly enable PDF/A. */\n attachments?: readonly PdfAttachment[];\n /** Preserves HTTP(S), mail, telephone, and FTP annotations unless explicitly set to `false`. */\n enableLinks?: boolean;\n /**\n * Rejects the caller at snapshot and render boundaries when aborted.\n * An already-running synchronous WASM render cannot be preempted.\n */\n signal?: AbortSignal;\n /** Receives coarse phase-boundary progress, not per-page render progress. */\n onProgress?: (progress: RenderProgress) => void;\n}\n\n/** Configuration whose lifetime matches an explicit renderer instance. */\nexport interface RendererInit {\n /** Execution backend. Defaults to `worker`. */\n execution?: \"worker\" | \"main\";\n /** WASM asset override for deployments that cannot serve package-relative assets. */\n wasmUrl?: string | URL;\n /** Embeddable TrueType fonts registered once for every render. */\n fonts?: readonly FontRegistration[];\n}\n\n/** Embeddable TrueType font registered in a renderer-owned WASM context. */\nexport interface FontRegistration {\n /** CSS family name used during font resolution. */\n family: string;\n /** Complete TrueType font bytes, copied into the native context. */\n data: ArrayBuffer | Uint8Array;\n /** CSS font weight. Defaults to `400`. */\n weight?: number | \"normal\" | \"bold\";\n /** CSS font style. Defaults to `normal`. */\n style?: \"normal\" | \"italic\";\n}\n\n/** Page settings accepted through the html2pdf.js-compatible `jsPDF` option. */\nexport interface CompatJsPdfOptions {\n /** Unit shared by custom page geometry and margins. */\n unit?: LengthUnit;\n /** Named or custom page format forwarded to the modern page contract. */\n format?: PageFormat;\n /** Page orientation forwarded to the modern page contract. */\n orientation?: PageOrientation;\n}\n\n/** Page-break settings accepted by the html2pdf.js compatibility layer. */\nexport interface CompatPageBreakOptions {\n /** Compatibility modes. Defaults to `css` and `legacy`. */\n mode?: \"css\" | \"legacy\" | \"avoid-all\" | readonly (\"css\" | \"legacy\" | \"avoid-all\")[];\n /** Selectors forced to begin on a new page. */\n before?: string | readonly string[];\n /** Selectors forced to end the current page. */\n after?: string | readonly string[];\n /** Selectors whose contents should avoid internal fragmentation. */\n avoid?: string | readonly string[];\n}\n\n/** Options supported by the PDF-oriented html2pdf.js compatibility layer. */\nexport interface Html2PdfOptions {\n /** Same metadata and archival options as RenderOptions. */\n metadata?: PdfMetadata;\n conformance?: \"pdfa-3u\";\n attachments?: readonly PdfAttachment[];\n /** Page margins in html2pdf.js order. */\n margin?: Margin;\n /** Filename used by `save` when no method argument is supplied. */\n filename?: string;\n /** Preserves HTTP(S), mail, telephone, and FTP links unless explicitly disabled. */\n enableLinks?: boolean;\n /** Compatibility pagination rules. */\n pagebreak?: CompatPageBreakOptions;\n /** Compatibility page geometry. */\n jsPDF?: CompatJsPdfOptions;\n /** Unsupported because this renderer does not use an html2canvas pipeline. */\n html2canvas?: never;\n /** Unsupported because PDF pages are not encoded as raster images. */\n image?: never;\n}\n\n/** Output encodings supported by compatibility `output` methods. */\nexport type PdfOutputType =\n | \"arraybuffer\"\n | \"blob\"\n | \"bloburl\"\n | \"bloburi\"\n | \"datauristring\"\n | \"dataurlstring\";\n\n/** File embedded in one PDF; caller data is copied and never transferred or detached. */\nexport interface PdfAttachment {\n /** Nonempty, unique filename. Unicode is preserved. */\n name: string;\n /** Original bytes; a Uint8Array embeds only its selected view. */\n data: ArrayBuffer | Uint8Array;\n /** MIME media type without parameters. Defaults to application/octet-stream. */\n mimeType?: string;\n /** Relationship to the document. Defaults to Unspecified. */\n relationship?: \"Source\" | \"Data\" | \"Alternative\" | \"Supplement\" | \"Unspecified\";\n /** Optional human-readable attachment description. */\n description?: string;\n /** Explicit modification time, stored in UTC with second precision; no date is invented. */\n modifiedAt?: Date;\n}\n"]}
|
package/dist/wasm.d.ts
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*
|
|
4
4
|
* @packageDocumentation
|
|
5
5
|
*/
|
|
6
|
+
import type { PdfExtras } from "./attachments.js";
|
|
6
7
|
import type { NormalizedPage } from "./page.js";
|
|
7
8
|
import type { CssProfile, Diagnostic, FontRegistration, PdfMetadata } from "./types.js";
|
|
8
9
|
import type { SnapshotPageMarginBox, SnapshotPageRule } from "./snapshot.js";
|
|
@@ -29,7 +30,7 @@ export declare class WasmBridge {
|
|
|
29
30
|
/** Instantiates the expected ABI, creates a context, and registers its fonts. */
|
|
30
31
|
static create(wasmUrl: string | URL, fonts?: readonly FontRegistration[]): Promise<WasmBridge>;
|
|
31
32
|
/** 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
|
+
render(html: string, page: NormalizedPage, metadata?: PdfMetadata, cssProfile?: CssProfile, marginBoxes?: readonly SnapshotPageMarginBox[], pageRules?: readonly SnapshotPageRule[], extras?: PdfExtras): WasmRenderResult;
|
|
33
34
|
/** Frees the renderer context and every font copied into it. */
|
|
34
35
|
dispose(): void;
|
|
35
36
|
/** Copies one font registration across the ABI into context-owned storage. */
|
package/dist/wasm.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* @packageDocumentation
|
|
5
5
|
*/
|
|
6
6
|
import { WasmRenderError } from "./errors.js";
|
|
7
|
-
const EXPECTED_ABI_VERSION =
|
|
7
|
+
const EXPECTED_ABI_VERSION = 2;
|
|
8
8
|
/**
|
|
9
9
|
* Owns one native PDF context and its registered fonts.
|
|
10
10
|
*
|
|
@@ -54,37 +54,42 @@ export class WasmBridge {
|
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
/** Serializes render options, invokes the native renderer, and returns owned output. */
|
|
57
|
-
render(html, page, metadata, cssProfile = "document", marginBoxes, pageRules) {
|
|
57
|
+
render(html, page, metadata, cssProfile = "document", marginBoxes, pageRules, extras) {
|
|
58
58
|
if (this.disposed)
|
|
59
59
|
throw new WasmRenderError("WASM bridge has been disposed", -15);
|
|
60
|
-
const
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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
|
-
}
|
|
60
|
+
const allocations = [];
|
|
61
|
+
const copy = (bytes) => {
|
|
62
|
+
const length = Math.max(bytes.length, 1);
|
|
63
|
+
const pointer = this.exports.alloc(length);
|
|
64
|
+
if (pointer === 0)
|
|
65
|
+
throw new WasmRenderError("WASM input allocation failed", -11);
|
|
66
|
+
allocations.push({ pointer, length });
|
|
67
|
+
new Uint8Array(this.exports.memory.buffer, pointer, bytes.length).set(bytes);
|
|
68
|
+
return pointer;
|
|
69
|
+
};
|
|
84
70
|
let resultHandle = 0;
|
|
85
71
|
try {
|
|
86
|
-
|
|
87
|
-
|
|
72
|
+
const attachments = extras?.attachments?.map(({ data, ...metadata }) => ({
|
|
73
|
+
...metadata, dataPointer: copy(data), dataLength: data.byteLength,
|
|
74
|
+
}));
|
|
75
|
+
const input = this.encoder.encode(html);
|
|
76
|
+
const inputPointer = copy(input);
|
|
77
|
+
const renderOptions = this.encoder.encode(JSON.stringify({
|
|
78
|
+
pageWidthPoints: page.widthPoints,
|
|
79
|
+
pageHeightPoints: page.heightPoints,
|
|
80
|
+
marginTopPoints: page.marginTopPoints,
|
|
81
|
+
marginRightPoints: page.marginRightPoints,
|
|
82
|
+
marginBottomPoints: page.marginBottomPoints,
|
|
83
|
+
marginLeftPoints: page.marginLeftPoints,
|
|
84
|
+
cssProfile, marginBoxes, pageRules,
|
|
85
|
+
conformance: extras?.conformance,
|
|
86
|
+
attachments,
|
|
87
|
+
metadata: metadata ? {
|
|
88
|
+
...metadata,
|
|
89
|
+
keywords: Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords,
|
|
90
|
+
} : undefined,
|
|
91
|
+
}));
|
|
92
|
+
const optionsPointer = copy(renderOptions);
|
|
88
93
|
resultHandle = this.exports.render_html_to_pdf_with_context_json_options(this.context, inputPointer, input.length, optionsPointer, renderOptions.length);
|
|
89
94
|
if (resultHandle === 0)
|
|
90
95
|
throw new WasmRenderError("WASM result allocation failed", -12);
|
|
@@ -106,8 +111,8 @@ export class WasmBridge {
|
|
|
106
111
|
finally {
|
|
107
112
|
if (resultHandle !== 0)
|
|
108
113
|
this.exports.pdf_result_free(resultHandle);
|
|
109
|
-
|
|
110
|
-
|
|
114
|
+
for (const { pointer, length } of allocations)
|
|
115
|
+
this.exports.free(pointer, length);
|
|
111
116
|
}
|
|
112
117
|
}
|
|
113
118
|
/** Frees the renderer context and every font copied into it. */
|
package/dist/wasm.js.map
CHANGED
|
@@ -1 +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,CAAC,WAAW,CAAC,MAAM,QAAQ,CAAC,WAAW,EAAE,EAAE,EAAE,CAAC,CAAC;QAC3E,CAAC;QAED,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,OAAiC,CAAC;QAClE,MAAM,UAAU,GAAG,OAAO,CAAC,wBAAwB,EAAE,EAAE,CAAC;QACxD,IAAI,UAAU,KAAK,oB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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"]}
|
|
1
|
+
{"version":3,"file":"wasm.js","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAK9C,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAuD/B;;;;;;;GAOG;AACH,MAAM,OAAO,UAAU;IAIgB,OAAO;I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O,CAAC,oBAAoB,CAAC,MAAM,CAAC;YAC3C,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,0BAA0B,CAAC,MAAM,CAAC,CAAC;QACpD,MAAM,MAAM,GAAG,IAAI,KAAK,OAAO;YAC7B,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,oBAAoB,CAAC,MAAM,CAAC;YAC3C,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,0BAA0B,CAAC,MAAM,CAAC,CAAC;QACpD,IAAI,OAAO,KAAK,CAAC,IAAI,MAAM,KAAK,CAAC;YAAE,OAAO,EAAE,CAAC;QAC7C,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC,CAAC;IAC/F,CAAC;IAEO,eAAe,CAAC,MAAc;QACpC,MAAM,UAAU,GAAG,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;QAChE,IAAI,CAAC,UAAU;YAAE,OAAO,EAAE,CAAC;QAC3B,IAAI,CAAC;YACH,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;YAC/C,OAAO,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAsB,CAAC,CAAC,CAAC,EAAE,CAAC;QAC7D,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 type { PdfExtras } from \"./attachments.js\";\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 = 2;\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[], extras?: PdfExtras): WasmRenderResult {\n if (this.disposed) throw new WasmRenderError(\"WASM bridge has been disposed\", -15);\n const allocations: { pointer: number; length: number }[] = [];\n const copy = (bytes: Uint8Array): number => {\n const length = Math.max(bytes.length, 1);\n const pointer = this.exports.alloc(length);\n if (pointer === 0) throw new WasmRenderError(\"WASM input allocation failed\", -11);\n allocations.push({ pointer, length });\n new Uint8Array(this.exports.memory.buffer, pointer, bytes.length).set(bytes);\n return pointer;\n };\n let resultHandle = 0;\n try {\n const attachments = extras?.attachments?.map(({ data, ...metadata }) => ({\n ...metadata, dataPointer: copy(data), dataLength: data.byteLength,\n }));\n const input = this.encoder.encode(html);\n const inputPointer = copy(input);\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, marginBoxes, pageRules,\n conformance: extras?.conformance,\n attachments,\n metadata: metadata ? {\n ...metadata,\n keywords: Array.isArray(metadata.keywords) ? metadata.keywords.join(\", \") : metadata.keywords,\n } : undefined,\n }));\n const optionsPointer = copy(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 for (const { pointer, length } of allocations) this.exports.free(pointer, 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"]}
|
package/dist/worker.js
CHANGED
|
@@ -1,9 +1,4 @@
|
|
|
1
1
|
/// <reference lib="webworker" />
|
|
2
|
-
/**
|
|
3
|
-
* Module Worker protocol that owns a `WasmBridge` off the browser main thread.
|
|
4
|
-
*
|
|
5
|
-
* @packageDocumentation
|
|
6
|
-
*/
|
|
7
2
|
import { WasmBridge } from "./wasm.js";
|
|
8
3
|
const scope = self;
|
|
9
4
|
let bridgePromise;
|
|
@@ -20,7 +15,7 @@ scope.addEventListener("message", (event) => {
|
|
|
20
15
|
scope.postMessage({ type: "render-error", id: message.id, error: "Worker is not initialized" });
|
|
21
16
|
return;
|
|
22
17
|
}
|
|
23
|
-
bridgePromise.then((bridge) => bridge.render(message.html, message.page, message.metadata, message.cssProfile, message.marginBoxes, message.pageRules)).then((result) => {
|
|
18
|
+
bridgePromise.then((bridge) => bridge.render(message.html, message.page, message.metadata, message.cssProfile, message.marginBoxes, message.pageRules, message.extras)).then((result) => {
|
|
24
19
|
scope.postMessage({ type: "render-result", id: message.id, bytes: result.bytes, pageCount: result.pageCount, diagnostics: result.diagnostics }, [result.bytes.buffer]);
|
|
25
20
|
}, (error) => scope.postMessage({ type: "render-error", id: message.id, error: errorMessage(error) }));
|
|
26
21
|
});
|
package/dist/worker.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,iCAAiC;
|
|
1
|
+
{"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,iCAAiC;AASjC,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAyBvC,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,CAAC,IAAI,CAAC;IAC3B,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;QAC5B,aAAa,GAAG,UAAU,CAAC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,CAAC;QAClE,aAAa,CAAC,IAAI,CAChB,GAAG,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,IA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AAY,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 type { PdfExtras } from \"./attachments.js\";\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 extras?: PdfExtras;\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, message.extras)).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
CHANGED
|
@@ -45,6 +45,34 @@ try {
|
|
|
45
45
|
Treat four-value margins as `[top, left, bottom, right]`, matching the
|
|
46
46
|
html2pdf.js compatibility API rather than CSS shorthand order.
|
|
47
47
|
|
|
48
|
+
## Archival output and attachments
|
|
49
|
+
|
|
50
|
+
Use `conformance: "pdfa-3u"` for PDF/A-3u, independently of `cssProfile`.
|
|
51
|
+
The existing renderer returns `PdfDocument` or throws; it never silently
|
|
52
|
+
falls back to ordinary PDF. Keep `metadata` on `RenderOptions`.
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
const pdf = await renderer.render(element, {
|
|
56
|
+
conformance: "pdfa-3u",
|
|
57
|
+
metadata: { title: "Invoice" },
|
|
58
|
+
attachments: [{ name: "invoice.xml", data: xmlBytes, mimeType: "application/xml", relationship: "Data" }],
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`attachments` also works on ordinary PDFs. Names must be nonempty and unique;
|
|
63
|
+
MIME defaults to `application/octet-stream`, relationship to `Unspecified`.
|
|
64
|
+
Allowed relationships are `Source`, `Data`, `Alternative`, `Supplement` and
|
|
65
|
+
`Unspecified`. Optional `description` and `modifiedAt: Date` are supported.
|
|
66
|
+
No modification date is synthesized. Only the selected Uint8Array view is
|
|
67
|
+
copied, and caller buffers remain usable with Worker execution.
|
|
68
|
+
|
|
69
|
+
PDF/A rejects CMYK JPEGs, missing/invalid Unicode glyph mappings, fonts that
|
|
70
|
+
forbid outline embedding, page dimensions outside 3–14400 points and PDF/A
|
|
71
|
+
string/name/graphics nesting limits. Fonts forbidding subsets embed fully.
|
|
72
|
+
Transparency and supported SVG remain native. This does not provide Tagged
|
|
73
|
+
PDF, PDF/UA, signatures, Factur-X or other attachment-specific conformance.
|
|
74
|
+
The compatibility adapter accepts the same options via `.set(...)`.
|
|
75
|
+
|
|
48
76
|
## Author production report templates
|
|
49
77
|
|
|
50
78
|
Define one page geometry contract. Prefer `page.margin` for application-owned
|