emf-converter 4.26.0 → 4.28.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.
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Normalises the inputs the public entry points accept into the plain
3
+ * `ArrayBuffer` the parsers read.
4
+ *
5
+ * - An `ArrayBuffer` is used as is.
6
+ * - A typed array, `DataView` or Node.js `Buffer` is copied out of its
7
+ * backing store when it covers only part of it. A Node `Buffer` is often a
8
+ * slice of a shared 8 KB pool, so passing `buf.buffer` would hand the
9
+ * parser someone else's bytes; accepting the view itself avoids that.
10
+ * - A `Blob` (or `File`) is read with `arrayBuffer()`.
11
+ * - Gzip-compressed metafiles (`.emz` / `.wmz`, as Office and Visio store
12
+ * them) are inflated with the platform's `DecompressionStream`.
13
+ *
14
+ * @module metafile-input
15
+ */
16
+ /** Every input form the `convertMetafile*` functions accept. */
17
+ type MetafileInput = ArrayBuffer | ArrayBufferView | Blob;
18
+
19
+ /**
20
+ * Public API: auto-detecting EMF/WMF conversion to PNG or SVG.
21
+ *
22
+ * The conversion pipeline for both formats and both outputs follows the same
23
+ * high-level steps:
24
+ * 1. Parse the file header to determine logical bounds and output dimensions
25
+ * (tried as EMF first, then WMF, to auto-detect the format).
26
+ * 2. Create a drawing surface: an in-memory canvas (OffscreenCanvas
27
+ * preferred, HTMLCanvasElement fallback, or the optional `@napi-rs/canvas`
28
+ * Node.js backend) for PNG output, or an {@link SvgContext} recorder for
29
+ * SVG output.
30
+ * 3. Replay every metafile record onto the surface in order.
31
+ * 4. Resolve "deferred images", bitmap / embedded-metafile draws that require
32
+ * async image decoding (via {@link createImageBitmap} or, in Node.js, the
33
+ * `@napi-rs/canvas` `loadImage` helper). SVG output embeds PNG/JPEG/GIF/
34
+ * WebP bytes verbatim and nested metafiles as nested SVG, with no decode.
35
+ * 5. Export: a `data:image/png;base64,...` URL, or an SVG tree that can be
36
+ * serialised to markup, a data URL, React elements, or JSX source.
37
+ *
38
+ * @module emf-converter
39
+ */
40
+
41
+ /**
42
+ * Configuration options for EMF/WMF conversion.
43
+ */
44
+ interface EmfConvertOptions {
45
+ /** WMF playback-device pixels per inch; defaults to 96 on each axis. */
46
+ wmfReferenceDpi?: number | {
47
+ x: number;
48
+ y: number;
49
+ };
50
+ /**
51
+ * ANSI code page of the playback device (Windows `GetACP()`), used for
52
+ * ANSI/DEFAULT charset text in EMF and WMF ANSI text records and for WMF
53
+ * LOGFONT face names, as Windows decodes them. Defaults to 1252.
54
+ * Supported values: 874, 932, 936, 949, 950, 1250..1258, 54936 and
55
+ * 65001. Other values fall back to 1252. Explicit text charsets keep
56
+ * their own code page.
57
+ */
58
+ ansiCodePage?: number;
59
+ /**
60
+ * OEM code page of the playback device (Windows `GetOEMCP()`), used for
61
+ * OEM_CHARSET text in EMF and WMF ANSI text records. Defaults to 437.
62
+ * Supported values: 437, 737, 775, 850, 852, 855, 858, 860, 861, 862,
63
+ * 863, 865, 866, 874, 932, 936, 949 and 950. Other values fall back to 437.
64
+ */
65
+ oemCodePage?: number;
66
+ /**
67
+ * ANSI code page of the WMF playback device only; overrides
68
+ * {@link ansiCodePage} for WMF input. Same values as `ansiCodePage`.
69
+ */
70
+ wmfAnsiCodePage?: number;
71
+ /** Maximum output width in pixels. */
72
+ maxWidth?: number;
73
+ /** Maximum output height in pixels. */
74
+ maxHeight?: number;
75
+ /**
76
+ * DPI scale factor for higher-resolution output.
77
+ * Default is 1 (1:1 pixel mapping). Values above 4 are clamped to 4 to
78
+ * prevent excessive memory usage.
79
+ */
80
+ dpiScale?: number;
81
+ /**
82
+ * Hard cap on the output canvas width/height in pixels. Guards against
83
+ * pathological metafiles. Defaults to {@link MAX_CANVAS_DIMENSION} (8192).
84
+ */
85
+ maxCanvasDimension?: number;
86
+ /**
87
+ * Maximum number of records processed per stream before replay stops.
88
+ * Defaults to 200,000 for GDI/WMF and 500,000 for the finer-grained EMF+
89
+ * stream. Supplying a value overrides both with the same cap.
90
+ */
91
+ maxRecords?: number;
92
+ /**
93
+ * Optional map from a (case-insensitive) Windows face name to a CSS font
94
+ * family available in the rendering environment, e.g. `{ calibri: 'Carlito',
95
+ * 'ms shell dlg': 'Tahoma' }`. Applied to GDI, WMF, and EMF+ text.
96
+ */
97
+ fontFamilyMap?: Record<string, string>;
98
+ /**
99
+ * Smooth shape edges instead of reproducing Windows' own rasterisation.
100
+ *
101
+ * PNG output defaults to `false`: plain-GDI vector shapes (Rectangle,
102
+ * Ellipse, RoundRect, Polygon, Polyline, arcs, bracketed paths, wide
103
+ * pens) are rasterised the way Windows GDI does, with its 28.4
104
+ * fixed-point geometry, fill rule, line algorithm and Bezier flattening,
105
+ * and EMF+ fills, strokes and clips follow the GDI+ `SmoothingMode` the
106
+ * file records (None, Default and HighSpeed aliased on GDI+'s pixel grid,
107
+ * AntiAlias and HighQuality with GDI+'s 8 x 4-sample antialiasing), so the
108
+ * PNG matches what Windows paints pixel for pixel.
109
+ *
110
+ * `true` draws every edge with Canvas's own antialiasing instead (still
111
+ * with GDI's geometry, pen widths, caps, joins and dash patterns), which
112
+ * looks smoother than Windows, especially for files recorded without
113
+ * GDI+ antialiasing.
114
+ *
115
+ * SVG output defaults to smooth vector edges (an SVG is meant to scale);
116
+ * `false` there embeds Windows' aliased shape pixels as image patches.
117
+ */
118
+ gdiAntialias?: boolean;
119
+ /**
120
+ * Font files to render GDI and WMF text with, exactly as Windows GDI
121
+ * does: TrueType `.ttf` / `.ttc` and raster `.fon` / `.fnt` bytes
122
+ * (`loadSystemFonts()` reads the installed ones in Node.js). The
123
+ * LOGFONT is realised against these files (face, weight, slant,
124
+ * `lfHeight`/`lfWidth`, charset fallback), each TrueType glyph is grid-fitted by the font's own TrueType
125
+ * instructions and scan-converted with TrueType dropout control
126
+ * (non-antialiased, 4x4 grayscale or ClearType per the LOGFONT's
127
+ * `lfQuality`), and glyphs are placed on GDI's integer device grid with
128
+ * GDI's own advance widths, cell metrics, underline and strike-out.
129
+ * Raster faces (MS Sans Serif, Helv, System, Terminal, ...) are drawn
130
+ * from their bitmaps at the size and whole-number stretch GDI picks.
131
+ * Supply the fonts the metafile names (for Windows-authored files, the
132
+ * matching files from `C:\Windows\Fonts`); a face that is missing is
133
+ * substituted the way GDI's font mapper would (by pitch and family),
134
+ * and without this option text is drawn with the canvas font engine.
135
+ * Ignored by SVG output, which keeps text as `<text>` but takes its
136
+ * per-glyph positions and metrics from these fonts.
137
+ */
138
+ fonts?: Array<ArrayBuffer | ArrayBufferView>;
139
+ /**
140
+ * Windows' system-wide font smoothing, which GDI applies to fonts that
141
+ * ask for `DEFAULT_QUALITY`, `DRAFT_QUALITY` or `PROOF_QUALITY` (most
142
+ * metafiles): `'cleartype'` (Windows' default), `'gray'` (standard
143
+ * antialiasing) or `'mono'` (smoothing off). GDI+ text with the
144
+ * SystemDefault rendering hint (EMF+ files without a TextRenderingHint)
145
+ * follows it too: ClearTypeGridFit, AntiAliasGridFit or single-bit
146
+ * grid-fitted. Only used with `fonts`.
147
+ */
148
+ fontSmoothing?: 'cleartype' | 'gray' | 'mono';
149
+ /**
150
+ * Cancels the conversion. When the signal aborts, the conversion stops and
151
+ * the returned promise rejects with `signal.reason` (as `fetch` does),
152
+ * which is different from the `null` that means "not a valid metafile".
153
+ * Replay checks the signal at every record and, while a signal is
154
+ * supplied, yields to the event loop about every 16 ms so that
155
+ * `AbortSignal.timeout()` timers and `abort()` calls from other tasks can
156
+ * fire mid-conversion. A single very long record (one huge bitmap blit)
157
+ * cannot be interrupted before it finishes. An already-aborted signal
158
+ * rejects immediately.
159
+ */
160
+ signal?: AbortSignal;
161
+ /**
162
+ * Wall-clock budget in milliseconds, counted from the call. When it runs
163
+ * out the promise rejects with a `DOMException` named `TimeoutError`, as
164
+ * `AbortSignal.timeout()` does. Checked at every record, so the overrun is
165
+ * at most one record's work (plus an encode, which is checked before it
166
+ * starts). Needs no event-loop turn: it works without a `signal`.
167
+ */
168
+ timeoutMs?: number;
169
+ }
170
+ /** Straight (non-premultiplied) RGBA pixels, row-major and top-down, like `ImageData`. */
171
+ interface RgbaImage {
172
+ data: Uint8ClampedArray;
173
+ width: number;
174
+ height: number;
175
+ }
176
+
177
+ /**
178
+ * The default DPI scale factor used for EMF/WMF rendering.
179
+ * Set to 1 for 1:1 pixel mapping (default).
180
+ * Set to 2 for HiDPI output (2x resolution).
181
+ */
182
+ declare const DEFAULT_DPI_SCALE = 1;
183
+
184
+ /**
185
+ * `emf-converter/lite`: a small browser build that renders EMF/WMF (with
186
+ * EMF+) to PNG through the page's canvas, for apps that only need a raster
187
+ * preview and care about bundle size.
188
+ *
189
+ * It replays every record the full build does, with these left out:
190
+ * - JPEG, WebP, SVG and PDF output;
191
+ * - the TrueType engine behind the `fonts` option: text is drawn with the
192
+ * canvas's `fillText` (use `fontFamilyMap` to pick installed or web fonts);
193
+ * - the bundled image decoders: embedded JPEG, GIF and WebP images are
194
+ * decoded by the browser, and TIFF images are not drawn;
195
+ * - Windows' measured colour tables (CMYK JPEG, `SetColorAdjustment`
196
+ * illuminants, GDI+ colour-curve effects) and the Johab code page.
197
+ *
198
+ * @packageDocumentation
199
+ */
200
+
201
+ /** {@link EmfConvertOptions} without the TrueType engine options the lite build has no use for. */
202
+ type LiteConvertOptions = Omit<EmfConvertOptions, 'fonts' | 'fontSmoothing'>;
203
+ /**
204
+ * Converts an EMF or WMF file (format auto-detected) to a PNG data URL, as
205
+ * the full build's `convertMetafileToDataUrl` does.
206
+ *
207
+ * @returns A `data:image/png;base64,...` string, or `null` when the input is
208
+ * not a valid metafile, has empty bounds, or no canvas is available.
209
+ */
210
+ declare function convertMetafileToDataUrl(input: MetafileInput, options?: LiteConvertOptions): Promise<string | null>;
211
+ /** Renders an EMF or WMF file to straight RGBA pixels, as the full build's `convertMetafileToImageData` does. */
212
+ declare function convertMetafileToImageData(input: MetafileInput, options?: LiteConvertOptions): Promise<RgbaImage | null>;
213
+
214
+ export { DEFAULT_DPI_SCALE, convertMetafileToDataUrl, convertMetafileToImageData };
215
+ export type { LiteConvertOptions, MetafileInput, RgbaImage };
package/dist/lite.d.ts ADDED
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Normalises the inputs the public entry points accept into the plain
3
+ * `ArrayBuffer` the parsers read.
4
+ *
5
+ * - An `ArrayBuffer` is used as is.
6
+ * - A typed array, `DataView` or Node.js `Buffer` is copied out of its
7
+ * backing store when it covers only part of it. A Node `Buffer` is often a
8
+ * slice of a shared 8 KB pool, so passing `buf.buffer` would hand the
9
+ * parser someone else's bytes; accepting the view itself avoids that.
10
+ * - A `Blob` (or `File`) is read with `arrayBuffer()`.
11
+ * - Gzip-compressed metafiles (`.emz` / `.wmz`, as Office and Visio store
12
+ * them) are inflated with the platform's `DecompressionStream`.
13
+ *
14
+ * @module metafile-input
15
+ */
16
+ /** Every input form the `convertMetafile*` functions accept. */
17
+ type MetafileInput = ArrayBuffer | ArrayBufferView | Blob;
18
+
19
+ /**
20
+ * Public API: auto-detecting EMF/WMF conversion to PNG or SVG.
21
+ *
22
+ * The conversion pipeline for both formats and both outputs follows the same
23
+ * high-level steps:
24
+ * 1. Parse the file header to determine logical bounds and output dimensions
25
+ * (tried as EMF first, then WMF, to auto-detect the format).
26
+ * 2. Create a drawing surface: an in-memory canvas (OffscreenCanvas
27
+ * preferred, HTMLCanvasElement fallback, or the optional `@napi-rs/canvas`
28
+ * Node.js backend) for PNG output, or an {@link SvgContext} recorder for
29
+ * SVG output.
30
+ * 3. Replay every metafile record onto the surface in order.
31
+ * 4. Resolve "deferred images", bitmap / embedded-metafile draws that require
32
+ * async image decoding (via {@link createImageBitmap} or, in Node.js, the
33
+ * `@napi-rs/canvas` `loadImage` helper). SVG output embeds PNG/JPEG/GIF/
34
+ * WebP bytes verbatim and nested metafiles as nested SVG, with no decode.
35
+ * 5. Export: a `data:image/png;base64,...` URL, or an SVG tree that can be
36
+ * serialised to markup, a data URL, React elements, or JSX source.
37
+ *
38
+ * @module emf-converter
39
+ */
40
+
41
+ /**
42
+ * Configuration options for EMF/WMF conversion.
43
+ */
44
+ interface EmfConvertOptions {
45
+ /** WMF playback-device pixels per inch; defaults to 96 on each axis. */
46
+ wmfReferenceDpi?: number | {
47
+ x: number;
48
+ y: number;
49
+ };
50
+ /**
51
+ * ANSI code page of the playback device (Windows `GetACP()`), used for
52
+ * ANSI/DEFAULT charset text in EMF and WMF ANSI text records and for WMF
53
+ * LOGFONT face names, as Windows decodes them. Defaults to 1252.
54
+ * Supported values: 874, 932, 936, 949, 950, 1250..1258, 54936 and
55
+ * 65001. Other values fall back to 1252. Explicit text charsets keep
56
+ * their own code page.
57
+ */
58
+ ansiCodePage?: number;
59
+ /**
60
+ * OEM code page of the playback device (Windows `GetOEMCP()`), used for
61
+ * OEM_CHARSET text in EMF and WMF ANSI text records. Defaults to 437.
62
+ * Supported values: 437, 737, 775, 850, 852, 855, 858, 860, 861, 862,
63
+ * 863, 865, 866, 874, 932, 936, 949 and 950. Other values fall back to 437.
64
+ */
65
+ oemCodePage?: number;
66
+ /**
67
+ * ANSI code page of the WMF playback device only; overrides
68
+ * {@link ansiCodePage} for WMF input. Same values as `ansiCodePage`.
69
+ */
70
+ wmfAnsiCodePage?: number;
71
+ /** Maximum output width in pixels. */
72
+ maxWidth?: number;
73
+ /** Maximum output height in pixels. */
74
+ maxHeight?: number;
75
+ /**
76
+ * DPI scale factor for higher-resolution output.
77
+ * Default is 1 (1:1 pixel mapping). Values above 4 are clamped to 4 to
78
+ * prevent excessive memory usage.
79
+ */
80
+ dpiScale?: number;
81
+ /**
82
+ * Hard cap on the output canvas width/height in pixels. Guards against
83
+ * pathological metafiles. Defaults to {@link MAX_CANVAS_DIMENSION} (8192).
84
+ */
85
+ maxCanvasDimension?: number;
86
+ /**
87
+ * Maximum number of records processed per stream before replay stops.
88
+ * Defaults to 200,000 for GDI/WMF and 500,000 for the finer-grained EMF+
89
+ * stream. Supplying a value overrides both with the same cap.
90
+ */
91
+ maxRecords?: number;
92
+ /**
93
+ * Optional map from a (case-insensitive) Windows face name to a CSS font
94
+ * family available in the rendering environment, e.g. `{ calibri: 'Carlito',
95
+ * 'ms shell dlg': 'Tahoma' }`. Applied to GDI, WMF, and EMF+ text.
96
+ */
97
+ fontFamilyMap?: Record<string, string>;
98
+ /**
99
+ * Smooth shape edges instead of reproducing Windows' own rasterisation.
100
+ *
101
+ * PNG output defaults to `false`: plain-GDI vector shapes (Rectangle,
102
+ * Ellipse, RoundRect, Polygon, Polyline, arcs, bracketed paths, wide
103
+ * pens) are rasterised the way Windows GDI does, with its 28.4
104
+ * fixed-point geometry, fill rule, line algorithm and Bezier flattening,
105
+ * and EMF+ fills, strokes and clips follow the GDI+ `SmoothingMode` the
106
+ * file records (None, Default and HighSpeed aliased on GDI+'s pixel grid,
107
+ * AntiAlias and HighQuality with GDI+'s 8 x 4-sample antialiasing), so the
108
+ * PNG matches what Windows paints pixel for pixel.
109
+ *
110
+ * `true` draws every edge with Canvas's own antialiasing instead (still
111
+ * with GDI's geometry, pen widths, caps, joins and dash patterns), which
112
+ * looks smoother than Windows, especially for files recorded without
113
+ * GDI+ antialiasing.
114
+ *
115
+ * SVG output defaults to smooth vector edges (an SVG is meant to scale);
116
+ * `false` there embeds Windows' aliased shape pixels as image patches.
117
+ */
118
+ gdiAntialias?: boolean;
119
+ /**
120
+ * Font files to render GDI and WMF text with, exactly as Windows GDI
121
+ * does: TrueType `.ttf` / `.ttc` and raster `.fon` / `.fnt` bytes
122
+ * (`loadSystemFonts()` reads the installed ones in Node.js). The
123
+ * LOGFONT is realised against these files (face, weight, slant,
124
+ * `lfHeight`/`lfWidth`, charset fallback), each TrueType glyph is grid-fitted by the font's own TrueType
125
+ * instructions and scan-converted with TrueType dropout control
126
+ * (non-antialiased, 4x4 grayscale or ClearType per the LOGFONT's
127
+ * `lfQuality`), and glyphs are placed on GDI's integer device grid with
128
+ * GDI's own advance widths, cell metrics, underline and strike-out.
129
+ * Raster faces (MS Sans Serif, Helv, System, Terminal, ...) are drawn
130
+ * from their bitmaps at the size and whole-number stretch GDI picks.
131
+ * Supply the fonts the metafile names (for Windows-authored files, the
132
+ * matching files from `C:\Windows\Fonts`); a face that is missing is
133
+ * substituted the way GDI's font mapper would (by pitch and family),
134
+ * and without this option text is drawn with the canvas font engine.
135
+ * Ignored by SVG output, which keeps text as `<text>` but takes its
136
+ * per-glyph positions and metrics from these fonts.
137
+ */
138
+ fonts?: Array<ArrayBuffer | ArrayBufferView>;
139
+ /**
140
+ * Windows' system-wide font smoothing, which GDI applies to fonts that
141
+ * ask for `DEFAULT_QUALITY`, `DRAFT_QUALITY` or `PROOF_QUALITY` (most
142
+ * metafiles): `'cleartype'` (Windows' default), `'gray'` (standard
143
+ * antialiasing) or `'mono'` (smoothing off). GDI+ text with the
144
+ * SystemDefault rendering hint (EMF+ files without a TextRenderingHint)
145
+ * follows it too: ClearTypeGridFit, AntiAliasGridFit or single-bit
146
+ * grid-fitted. Only used with `fonts`.
147
+ */
148
+ fontSmoothing?: 'cleartype' | 'gray' | 'mono';
149
+ /**
150
+ * Cancels the conversion. When the signal aborts, the conversion stops and
151
+ * the returned promise rejects with `signal.reason` (as `fetch` does),
152
+ * which is different from the `null` that means "not a valid metafile".
153
+ * Replay checks the signal at every record and, while a signal is
154
+ * supplied, yields to the event loop about every 16 ms so that
155
+ * `AbortSignal.timeout()` timers and `abort()` calls from other tasks can
156
+ * fire mid-conversion. A single very long record (one huge bitmap blit)
157
+ * cannot be interrupted before it finishes. An already-aborted signal
158
+ * rejects immediately.
159
+ */
160
+ signal?: AbortSignal;
161
+ /**
162
+ * Wall-clock budget in milliseconds, counted from the call. When it runs
163
+ * out the promise rejects with a `DOMException` named `TimeoutError`, as
164
+ * `AbortSignal.timeout()` does. Checked at every record, so the overrun is
165
+ * at most one record's work (plus an encode, which is checked before it
166
+ * starts). Needs no event-loop turn: it works without a `signal`.
167
+ */
168
+ timeoutMs?: number;
169
+ }
170
+ /** Straight (non-premultiplied) RGBA pixels, row-major and top-down, like `ImageData`. */
171
+ interface RgbaImage {
172
+ data: Uint8ClampedArray;
173
+ width: number;
174
+ height: number;
175
+ }
176
+
177
+ /**
178
+ * The default DPI scale factor used for EMF/WMF rendering.
179
+ * Set to 1 for 1:1 pixel mapping (default).
180
+ * Set to 2 for HiDPI output (2x resolution).
181
+ */
182
+ declare const DEFAULT_DPI_SCALE = 1;
183
+
184
+ /**
185
+ * `emf-converter/lite`: a small browser build that renders EMF/WMF (with
186
+ * EMF+) to PNG through the page's canvas, for apps that only need a raster
187
+ * preview and care about bundle size.
188
+ *
189
+ * It replays every record the full build does, with these left out:
190
+ * - JPEG, WebP, SVG and PDF output;
191
+ * - the TrueType engine behind the `fonts` option: text is drawn with the
192
+ * canvas's `fillText` (use `fontFamilyMap` to pick installed or web fonts);
193
+ * - the bundled image decoders: embedded JPEG, GIF and WebP images are
194
+ * decoded by the browser, and TIFF images are not drawn;
195
+ * - Windows' measured colour tables (CMYK JPEG, `SetColorAdjustment`
196
+ * illuminants, GDI+ colour-curve effects) and the Johab code page.
197
+ *
198
+ * @packageDocumentation
199
+ */
200
+
201
+ /** {@link EmfConvertOptions} without the TrueType engine options the lite build has no use for. */
202
+ type LiteConvertOptions = Omit<EmfConvertOptions, 'fonts' | 'fontSmoothing'>;
203
+ /**
204
+ * Converts an EMF or WMF file (format auto-detected) to a PNG data URL, as
205
+ * the full build's `convertMetafileToDataUrl` does.
206
+ *
207
+ * @returns A `data:image/png;base64,...` string, or `null` when the input is
208
+ * not a valid metafile, has empty bounds, or no canvas is available.
209
+ */
210
+ declare function convertMetafileToDataUrl(input: MetafileInput, options?: LiteConvertOptions): Promise<string | null>;
211
+ /** Renders an EMF or WMF file to straight RGBA pixels, as the full build's `convertMetafileToImageData` does. */
212
+ declare function convertMetafileToImageData(input: MetafileInput, options?: LiteConvertOptions): Promise<RgbaImage | null>;
213
+
214
+ export { DEFAULT_DPI_SCALE, convertMetafileToDataUrl, convertMetafileToImageData };
215
+ export type { LiteConvertOptions, MetafileInput, RgbaImage };