@imggion/html2realpdf 0.3.1 → 0.3.2
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 +0 -3
- package/dist/libhtml2realpdf.wasm +0 -0
- package/dist/snapshot.js +126 -5
- package/dist/snapshot.js.map +1 -1
- package/dist/types.d.ts +10 -2
- package/dist/types.js.map +1 -1
- package/dist/wasm.js +6 -0
- package/dist/wasm.js.map +1 -1
- package/package.json +1 -1
- package/skills/html2realpdf/SKILL.md +6 -2
package/dist/types.d.ts
CHANGED
|
@@ -231,9 +231,17 @@ export interface RendererInit {
|
|
|
231
231
|
export interface FontRegistration {
|
|
232
232
|
/** CSS family name used during font resolution. */
|
|
233
233
|
family: string;
|
|
234
|
-
/**
|
|
234
|
+
/**
|
|
235
|
+
* Complete TrueType (`glyf` outline) font bytes, copied into the native
|
|
236
|
+
* context. WOFF/WOFF2 files are rejected with a descriptive error.
|
|
237
|
+
*/
|
|
235
238
|
data: ArrayBuffer | Uint8Array;
|
|
236
|
-
/**
|
|
239
|
+
/**
|
|
240
|
+
* CSS font weight from 1 to 1000. Defaults to `400`. Faces of one family are
|
|
241
|
+
* selected with the CSS font-matching algorithm, so Medium (500) and
|
|
242
|
+
* SemiBold (600) coexist with Regular and Bold; registering the same family,
|
|
243
|
+
* weight, and style again replaces the earlier face.
|
|
244
|
+
*/
|
|
237
245
|
weight?: number | "normal" | "bold";
|
|
238
246
|
/** CSS font style. Defaults to `normal`. */
|
|
239
247
|
style?: "normal" | "italic";
|
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` denies the resource without a fallback fetch:\n * `resourcePolicy: \"error\"` rejects the render and `\"omit\"` omits the resource.\n * Without a resolver, images may be fetched directly; HTML-string stylesheets\n * require a resolver. Already embedded image data URLs bypass the resolver.\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"]}
|
|
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` denies the resource without a fallback fetch:\n * `resourcePolicy: \"error\"` rejects the render and `\"omit\"` omits the resource.\n * Without a resolver, images may be fetched directly; HTML-string stylesheets\n * require a resolver. Already embedded image data URLs bypass the resolver.\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 /**\n * Complete TrueType (`glyf` outline) font bytes, copied into the native\n * context. WOFF/WOFF2 files are rejected with a descriptive error.\n */\n data: ArrayBuffer | Uint8Array;\n /**\n * CSS font weight from 1 to 1000. Defaults to `400`. Faces of one family are\n * selected with the CSS font-matching algorithm, so Medium (500) and\n * SemiBold (600) coexist with Regular and Bold; registering the same family,\n * weight, and style again replaces the earlier face.\n */\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.js
CHANGED
|
@@ -147,6 +147,12 @@ export class WasmBridge {
|
|
|
147
147
|
: new Uint8Array(registration.data);
|
|
148
148
|
if (family.length === 0 || data.length === 0)
|
|
149
149
|
throw new WasmRenderError("Font family and data must not be empty", -16);
|
|
150
|
+
// WOFF and WOFF2 wrap compressed tables that the native TrueType parser
|
|
151
|
+
// cannot read. Keep the native invalid-font status, but name the cause.
|
|
152
|
+
const signature = data.length >= 4 ? String.fromCharCode(data[0], data[1], data[2], data[3]) : "";
|
|
153
|
+
if (signature === "wOFF" || signature === "wOF2") {
|
|
154
|
+
throw new WasmRenderError(`Font "${registration.family}" is ${signature === "wOF2" ? "WOFF2" : "WOFF"}; register the TrueType (.ttf) file instead`, -6);
|
|
155
|
+
}
|
|
150
156
|
const familyPointer = this.exports.alloc(family.length);
|
|
151
157
|
const dataPointer = this.exports.alloc(data.length);
|
|
152
158
|
if (familyPointer === 0 || dataPointer === 0) {
|
package/dist/wasm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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;AAC/B,kFAAkF;AAClF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,EAAE,CAAC;AAuDpC;;;;;;;;GAQG;AACH,MAAM,OAAO,UAAU;IAIgB,OAAO;IAAgC,OAAO;IAHlE,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IACrC,QAAQ,GAAG,KAAK,CAAC;IAEzB,YAAqC,OAAoB,EAAmB,OAAe;uBAAtD,OAAO;uBAAgC,OAAO;IAAW,CAAC;IAE/F,iFAAiF;IACjF,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,OAAqB,EAAE,KAAK,GAAgC,EAAE;QAChF,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,OAAO,CAAC,CAAC;QACtC,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AC,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/** Internal status: the instance must be discarded without further WASM calls. */\nexport const WASM_TRAP_STATUS = -23;\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. After a WASM trap the whole instance is\n * discarded without further calls, including cleanup against damaged state.\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 try {\n return bridge.rethrow(error);\n } finally {\n bridge.dispose();\n }\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 } catch (error) {\n return this.rethrow(error);\n } finally {\n if (!this.disposed) {\n try {\n if (resultHandle !== 0) this.exports.pdf_result_free(resultHandle);\n for (const { pointer, length } of allocations) this.exports.free(pointer, length);\n } catch (error) {\n this.rethrow(error);\n }\n }\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 } catch (error) {\n this.rethrow(error);\n } finally {\n if (!this.disposed) {\n try {\n this.exports.free(familyPointer, family.length);\n this.exports.free(dataPointer, data.length);\n } catch (error) {\n this.rethrow(error);\n }\n }\n }\n }\n\n private rethrow(error: unknown): never {\n if (error instanceof WebAssembly.RuntimeError) {\n // A trap may leave the stack or allocator invalid, including during free.\n this.disposed = true;\n throw new WasmRenderError(`WASM instance was discarded after a trap: ${error.message}`, WASM_TRAP_STATUS, { cause: error });\n }\n throw error;\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;AAC/B,kFAAkF;AAClF,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,EAAE,CAAC;AAuDpC;;;;;;;;GAQG;AACH,MAAM,OAAO,UAAU;IAIgB,OAAO;IAAgC,OAAO;IAHlE,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IACrC,QAAQ,GAAG,KAAK,CAAC;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ridge 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/** Internal status: the instance must be discarded without further WASM calls. */\nexport const WASM_TRAP_STATUS = -23;\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. After a WASM trap the whole instance is\n * discarded without further calls, including cleanup against damaged state.\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 try {\n return bridge.rethrow(error);\n } finally {\n bridge.dispose();\n }\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 } catch (error) {\n return this.rethrow(error);\n } finally {\n if (!this.disposed) {\n try {\n if (resultHandle !== 0) this.exports.pdf_result_free(resultHandle);\n for (const { pointer, length } of allocations) this.exports.free(pointer, length);\n } catch (error) {\n this.rethrow(error);\n }\n }\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 // WOFF and WOFF2 wrap compressed tables that the native TrueType parser\n // cannot read. Keep the native invalid-font status, but name the cause.\n const signature = data.length >= 4 ? String.fromCharCode(data[0]!, data[1]!, data[2]!, data[3]!) : \"\";\n if (signature === \"wOFF\" || signature === \"wOF2\") {\n throw new WasmRenderError(\n `Font \"${registration.family}\" is ${signature === \"wOF2\" ? \"WOFF2\" : \"WOFF\"}; register the TrueType (.ttf) file instead`,\n -6,\n );\n }\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 } catch (error) {\n this.rethrow(error);\n } finally {\n if (!this.disposed) {\n try {\n this.exports.free(familyPointer, family.length);\n this.exports.free(dataPointer, data.length);\n } catch (error) {\n this.rethrow(error);\n }\n }\n }\n }\n\n private rethrow(error: unknown): never {\n if (error instanceof WebAssembly.RuntimeError) {\n // A trap may leave the stack or allocator invalid, including during free.\n this.disposed = true;\n throw new WasmRenderError(`WASM instance was discarded after a trap: ${error.message}`, WASM_TRAP_STATUS, { cause: error });\n }\n throw error;\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/package.json
CHANGED
|
@@ -323,8 +323,12 @@ Pass only renderer-owned resources and execution settings to `createRenderer`:
|
|
|
323
323
|
| `fonts` | `FontRegistration[]`; none by default | Register reusable TrueType faces once for every render owned by this renderer. |
|
|
324
324
|
|
|
325
325
|
Configure each font registration with `family`, binary `data`, optional
|
|
326
|
-
`weight` (`400` by default,
|
|
327
|
-
|
|
326
|
+
`weight` (`400` by default, any CSS weight from `1` to `1000`, or
|
|
327
|
+
`"normal"`/`"bold"`), and optional `style` (`"normal"` by default or
|
|
328
|
+
`"italic"`). Register one face per weight you use, such as Regular `400`,
|
|
329
|
+
Medium `500`, and SemiBold `600`: faces are chosen with CSS font matching, and
|
|
330
|
+
only the same family, weight, and style replaces an earlier face. Pass
|
|
331
|
+
TrueType (`.ttf`) bytes; WOFF and WOFF2 files are rejected.
|
|
328
332
|
|
|
329
333
|
### Per-render options
|
|
330
334
|
|