@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/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 = 1;
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 input = this.encoder.encode(html);
61
- const renderOptions = this.encoder.encode(JSON.stringify({
62
- pageWidthPoints: page.widthPoints,
63
- pageHeightPoints: page.heightPoints,
64
- marginTopPoints: page.marginTopPoints,
65
- marginRightPoints: page.marginRightPoints,
66
- marginBottomPoints: page.marginBottomPoints,
67
- marginLeftPoints: page.marginLeftPoints,
68
- cssProfile,
69
- marginBoxes,
70
- pageRules,
71
- metadata: metadata ? {
72
- ...metadata,
73
- keywords: Array.isArray(metadata.keywords) ? metadata.keywords.join(", ") : metadata.keywords,
74
- } : undefined,
75
- }));
76
- const inputPointer = this.exports.alloc(input.length);
77
- if (inputPointer === 0)
78
- throw new WasmRenderError("WASM input allocation failed", -11);
79
- const optionsPointer = this.exports.alloc(renderOptions.length);
80
- if (optionsPointer === 0) {
81
- this.exports.free(inputPointer, input.length);
82
- throw new WasmRenderError("WASM options allocation failed", -11);
83
- }
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
- new Uint8Array(this.exports.memory.buffer, inputPointer, input.length).set(input);
87
- new Uint8Array(this.exports.memory.buffer, optionsPointer, renderOptions.length).set(renderOptions);
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
- this.exports.free(inputPointer, input.length);
110
- this.exports.free(optionsPointer, renderOptions.length);
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":"A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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 { 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;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,CAA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C,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
  });
@@ -1 +1 @@
1
- {"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,iCAAiC;AAEjC;;;;GAIG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAwBvC,MAAM,KAAK,GAAG,IAA6C,CAAC;AAC5D,IAAI,aAA8C,CAAC;AAEnD,6EAA6E;AAC7E,mEAAmE;AACnE,KAAK,CAAC,gBAAgB,CAAC,SAAS,EAAE,CAAC,KAAgD,EAAE,EAAE;IACrF,MAAM,OAAO,GAAG,KAAK,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,IAAI,EAAE,OAAO,EAAE,CAAC,EAC1C,CAAC,KAAc,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAC1F,CAAC;QACF,OAAO;IACT,CAAC;IAED,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,KAAK,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,EAAE,2BAA2B,EAAE,CAAC,CAAC;QAChG,OAAO;IACT,CAAC;IAED,aAAa,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,UAAU,EAAE,OAAO,CAAC,WAAW,EAAE,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAC1J,CAAC,MAAM,EAAE,EAAE;QACT,KAAK,CAAC,WAAW,CACf,EAAE,IAAI,EAAE,eAAe,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,EAAE,SAAS,EAAE,MAAM,CAAC,SAAS,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,EAAE,EAC5H,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CACtB,CAAC;IACJ,CAAC,EACD,CAAC,KAAc,EAAE,EAAE,CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAC5G,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/// <reference lib=\"webworker\" />\n\n/**\n * Module Worker protocol that owns a `WasmBridge` off the browser main thread.\n *\n * @packageDocumentation\n */\n\nimport { WasmBridge } from \"./wasm.js\";\nimport type { NormalizedPage } from \"./page.js\";\nimport type { CssProfile, FontRegistration, PdfMetadata } from \"./types.js\";\nimport type { SnapshotPageMarginBox, SnapshotPageRule } from \"./snapshot.js\";\n\n/** Creates the single renderer context owned by this Worker. */\ninterface InitMessage {\n type: \"init\";\n wasmUrl: string;\n fonts: readonly FontRegistration[];\n}\n\n/** Requests one render and correlates its transferable result by `id`. */\ninterface RenderMessage {\n type: \"render\";\n id: number;\n html: string;\n page: NormalizedPage;\n metadata?: PdfMetadata;\n cssProfile?: CssProfile;\n marginBoxes?: readonly SnapshotPageMarginBox[];\n pageRules?: readonly SnapshotPageRule[];\n}\n\nconst scope = self as unknown as DedicatedWorkerGlobalScope;\nlet bridgePromise: Promise<WasmBridge> | undefined;\n\n// Initialization and renders share the same promise so early render requests\n// wait for font registration instead of racing the native context.\nscope.addEventListener(\"message\", (event: MessageEvent<InitMessage | RenderMessage>) => {\n const message = event.data;\n if (message.type === \"init\") {\n bridgePromise = WasmBridge.create(message.wasmUrl, message.fonts);\n bridgePromise.then(\n () => scope.postMessage({ type: \"ready\" }),\n (error: unknown) => scope.postMessage({ type: \"init-error\", error: errorMessage(error) }),\n );\n return;\n }\n\n if (!bridgePromise) {\n scope.postMessage({ type: \"render-error\", id: message.id, error: \"Worker is not initialized\" });\n return;\n }\n\n bridgePromise.then((bridge) => bridge.render(message.html, message.page, message.metadata, message.cssProfile, message.marginBoxes, message.pageRules)).then(\n (result) => {\n scope.postMessage(\n { type: \"render-result\", id: message.id, bytes: result.bytes, pageCount: result.pageCount, diagnostics: result.diagnostics },\n [result.bytes.buffer],\n );\n },\n (error: unknown) => scope.postMessage({ type: \"render-error\", id: message.id, error: errorMessage(error) }),\n );\n});\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"]}
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;IA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CAAC,KAAK,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,EAAE,KAAK,EAAE,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC,CAC5G,CAAC;AACJ,CAAC,CAAC,CAAC;AAEH,SAAS,YAAY,CAAC,KAAc;IAClC,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/// <reference lib=\"webworker\" />\n\n/**\n * Module Worker protocol that owns a `WasmBridge` off the browser main thread.\n *\n * @packageDocumentation\n */\n\nimport 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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imggion/html2realpdf",
3
- "version": "0.1.14",
3
+ "version": "0.3.0",
4
4
  "description": "Browser-first HTML to real, selectable PDF rendering powered by Zig and WebAssembly",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -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
@@ -348,7 +376,7 @@ Pass these options to `PdfDocument.preview`:
348
376
 
349
377
  | Option | Values and default |
350
378
  | --- | --- |
351
- | `showToolbar` | `true` by default; set to `false` to hide the summary and zoom controls |
379
+ | `showToolbar` | `true` by default; set to `false` to hide page navigation and zoom controls |
352
380
  | `padding` | Non-negative CSS pixel value; `28` by default and `16` on narrow screens |
353
381
  | `initialScale` | `"fit-width"` (default) or a numeric scale |
354
382
  | `minScale` | `0.25` by default, clamped to at least `0.1` |
@@ -357,6 +385,7 @@ Pass these options to `PdfDocument.preview`:
357
385
  | `maxPixelRatio` | `2` by default; caps page-canvas device pixel ratio |
358
386
  | `ariaLabel` | `"PDF preview"` by default |
359
387
  | `onProgress` | Callback after each page canvas completes |
388
+ | `onPageChange` | Callback after initial loading and whenever the 1-based current page changes |
360
389
 
361
390
  ### html2pdf.js compatibility options
362
391
 
@@ -421,8 +450,16 @@ all previews it owns.
421
450
  ```ts
422
451
  const preview = await pdf.preview(document.querySelector("#preview")!, {
423
452
  initialScale: "fit-width",
453
+ onPageChange(currentPage, totalPages) {
454
+ document.querySelector("#page-count")!.textContent = `Page ${currentPage} of ${totalPages}`;
455
+ },
424
456
  });
425
457
 
458
+ document.querySelector("#previous")!.addEventListener("click", () => preview.previousPage());
459
+ document.querySelector("#next")!.addEventListener("click", () => preview.nextPage());
460
+ preview.goToPage(7); // Clamped to the first or last page when outside the document range.
461
+ console.log(preview.currentPage);
462
+
426
463
  preview.dispose();
427
464
  pdf.dispose();
428
465
  ```