@imggion/html2realpdf 0.1.14 → 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 +78 -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/preview.d.ts +26 -1
- package/dist/preview.js +170 -13
- package/dist/preview.js.map +1 -1
- package/dist/renderer.js +14 -5
- package/dist/renderer.js.map +1 -1
- package/dist/snapshot.js +44 -25
- package/dist/snapshot.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 +38 -1
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)
|
|
@@ -159,11 +167,24 @@ HTML copy.
|
|
|
159
167
|
const pdf = await renderPdf(invoice);
|
|
160
168
|
const previewTarget = document.querySelector<HTMLElement>("#pdf-preview");
|
|
161
169
|
if (!previewTarget) throw new Error("Preview target not found");
|
|
170
|
+
const previousButton = document.querySelector<HTMLButtonElement>("#previous-page")!;
|
|
171
|
+
const nextButton = document.querySelector<HTMLButtonElement>("#next-page")!;
|
|
172
|
+
const pageCounter = document.querySelector<HTMLOutputElement>("#page-counter")!;
|
|
162
173
|
|
|
163
174
|
const preview = await pdf.preview(previewTarget, {
|
|
164
175
|
initialScale: "fit-width",
|
|
176
|
+
onPageChange(currentPage, totalPages) {
|
|
177
|
+
pageCounter.textContent = `Page ${currentPage} of ${totalPages}`;
|
|
178
|
+
previousButton.disabled = currentPage === 1;
|
|
179
|
+
nextButton.disabled = currentPage === totalPages;
|
|
180
|
+
},
|
|
165
181
|
});
|
|
166
182
|
|
|
183
|
+
previousButton.addEventListener("click", () => preview.previousPage());
|
|
184
|
+
nextButton.addEventListener("click", () => preview.nextPage());
|
|
185
|
+
preview.goToPage(7); // Clamped to the first or last page when outside the document range.
|
|
186
|
+
console.log(preview.currentPage); // 1-based and synchronized with manual scrolling
|
|
187
|
+
|
|
167
188
|
// Later, when closing the preview:
|
|
168
189
|
preview.dispose();
|
|
169
190
|
pdf.dispose();
|
|
@@ -193,6 +214,58 @@ const pdf = await renderPdf(postcard, {
|
|
|
193
214
|
});
|
|
194
215
|
```
|
|
195
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
|
+
|
|
196
269
|
## Benchmark
|
|
197
270
|
|
|
198
271
|
One recorded run of the deterministic 30-page stress report produced:
|
|
@@ -211,7 +284,8 @@ One recorded run of the deterministic 30-page stress report produced:
|
|
|
211
284
|
|
|
212
285
|
## Contributing
|
|
213
286
|
|
|
214
|
-
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,
|
|
215
289
|
install the JavaScript dependencies once:
|
|
216
290
|
|
|
217
291
|
```sh
|
|
@@ -227,6 +301,7 @@ npm ci --prefix tests/web
|
|
|
227
301
|
| `make wasm` | Build the default `ReleaseFast` WebAssembly and browser package |
|
|
228
302
|
| `make wasm-small` | Build the optional size-oriented `ReleaseSmall` package asset |
|
|
229
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 |
|
|
230
305
|
| `make test-release` | Run the complete release gate |
|
|
231
306
|
|
|
232
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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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,"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;YACzD,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAChC,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,WAAW,CAAC;SACtC,CAAC;QACF,IAAI,OAAO,CAAC,SAAS,CAAC,MAAM,KAAK,SAAS;YAAE,SAAS,CAAC,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC;QACxF,IAAI,OAAO,CAAC,SAAS,CAAC,KAAK,KAAK,SAAS;YAAE,SAAS,CAAC,KAAK,GAAG,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC;QACrF,IAAI,OAAO,CAAC,SAAS,CAAC,KAAK,KAAK,SAAS;YAAE,SAAS,CAAC,KAAK,GAAG,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC;QACrF,aAAa,CAAC,SAAS,GAAG,SAAS,CAAC;IACtC,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAID,SAAS,aAAa,CAAC,IAAU;IAC/B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAChC,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACtF,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,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","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,E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ACzD,MAAM,EAAE,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC;YAChC,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,WAAW,CAAC;SACtC,CAAC;QACF,IAAI,OAAO,CAAC,SAAS,CAAC,MAAM,KAAK,SAAS;YAAE,SAAS,CAAC,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC;QACxF,IAAI,OAAO,CAAC,SAAS,CAAC,KAAK,KAAK,SAAS;YAAE,SAAS,CAAC,KAAK,GAAG,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC;QACrF,IAAI,OAAO,CAAC,SAAS,CAAC,KAAK,KAAK,SAAS;YAAE,SAAS,CAAC,KAAK,GAAG,OAAO,CAAC,SAAS,CAAC,KAAK,CAAC;QACrF,aAAa,CAAC,SAAS,GAAG,SAAS,CAAC;IACtC,CAAC;IACD,OAAO,aAAa,CAAC;AACvB,CAAC;AAID,SAAS,aAAa,CAAC,IAAU;IAC/B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAChC,MAAM,CAAC,gBAAgB,CAAC,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACtF,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,MAAM,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/preview.d.ts
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
export type PdfPreviewTheme = "system" | "light" | "dark";
|
|
8
8
|
/** Display and rendering limits for `PdfDocument.preview`. */
|
|
9
9
|
export interface PdfPreviewOptions {
|
|
10
|
-
/** Whether to show the page
|
|
10
|
+
/** Whether to show the page navigation and zoom toolbar. Defaults to `true`. */
|
|
11
11
|
showToolbar?: boolean;
|
|
12
12
|
/** Padding around the rendered pages in CSS pixels. Defaults to `28`, or `16` on narrow screens. */
|
|
13
13
|
padding?: number;
|
|
@@ -27,6 +27,8 @@ export interface PdfPreviewOptions {
|
|
|
27
27
|
theme?: PdfPreviewTheme;
|
|
28
28
|
/** Called after each page canvas completes rendering. */
|
|
29
29
|
onProgress?: (completedPages: number, totalPages: number) => void;
|
|
30
|
+
/** Called once after initial loading and whenever the 1-based current page changes. */
|
|
31
|
+
onPageChange?: (currentPage: number, totalPages: number) => void;
|
|
30
32
|
}
|
|
31
33
|
/**
|
|
32
34
|
* Interactive canvas preview created and owned by a `PdfDocument`.
|
|
@@ -46,6 +48,8 @@ export declare class PdfPreview {
|
|
|
46
48
|
private readonly shadow;
|
|
47
49
|
private readonly pagesElement;
|
|
48
50
|
private readonly summaryElement;
|
|
51
|
+
private readonly previousPageButton;
|
|
52
|
+
private readonly nextPageButton;
|
|
49
53
|
private readonly scaleElement;
|
|
50
54
|
private readonly zoomOutButton;
|
|
51
55
|
private readonly zoomInButton;
|
|
@@ -54,15 +58,25 @@ export declare class PdfPreview {
|
|
|
54
58
|
private readonly zoomStep;
|
|
55
59
|
private readonly pixelRatio;
|
|
56
60
|
private readonly onProgress;
|
|
61
|
+
private readonly onPageChange;
|
|
62
|
+
private readonly events;
|
|
57
63
|
private loadingTask;
|
|
58
64
|
private document;
|
|
59
65
|
private renderTask;
|
|
60
66
|
private scale;
|
|
67
|
+
private currentPageValue;
|
|
61
68
|
private renderVersion;
|
|
69
|
+
private scrollFrame;
|
|
70
|
+
private scrollDetectionSuspended;
|
|
71
|
+
private rendering;
|
|
72
|
+
private emittedInitialPageChange;
|
|
62
73
|
private disposed;
|
|
74
|
+
private readonly handleScroll;
|
|
63
75
|
private constructor();
|
|
64
76
|
/** Current logical PDF.js scale after option clamping. */
|
|
65
77
|
get currentScale(): number;
|
|
78
|
+
/** Current 1-based page, synchronized with navigation and manual preview scrolling. */
|
|
79
|
+
get currentPage(): number;
|
|
66
80
|
/** Current preview-control theme, including the default `system` mode. */
|
|
67
81
|
get currentTheme(): PdfPreviewTheme;
|
|
68
82
|
/** Updates the preview-control theme without rerendering the PDF pages. */
|
|
@@ -71,6 +85,12 @@ export declare class PdfPreview {
|
|
|
71
85
|
setScale(value: number): Promise<void>;
|
|
72
86
|
/** Fits the first page to the available viewer width and rerenders all pages. */
|
|
73
87
|
fitToWidth(): Promise<void>;
|
|
88
|
+
/** Navigates to the preceding page without scrolling the host document. */
|
|
89
|
+
previousPage(): void;
|
|
90
|
+
/** Navigates to the following page without scrolling the host document. */
|
|
91
|
+
nextPage(): void;
|
|
92
|
+
/** Navigates to a 1-based page, clamped to the available document range. */
|
|
93
|
+
goToPage(page: number): void;
|
|
74
94
|
/** Cancels active work, destroys PDF.js state, and clears the target. */
|
|
75
95
|
dispose(): void;
|
|
76
96
|
private load;
|
|
@@ -80,6 +100,11 @@ export declare class PdfPreview {
|
|
|
80
100
|
*/
|
|
81
101
|
private renderPages;
|
|
82
102
|
private updateControls;
|
|
103
|
+
private navigateToPage;
|
|
104
|
+
private commitCurrentPage;
|
|
105
|
+
private scrollPageIntoView;
|
|
106
|
+
private detectCurrentPage;
|
|
107
|
+
private suspendScrollDetection;
|
|
83
108
|
private availablePageWidth;
|
|
84
109
|
private showError;
|
|
85
110
|
private releaseDocument;
|