emf-converter 3.3.0 → 3.5.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/index.d.ts CHANGED
@@ -1,20 +1,109 @@
1
1
  /**
2
- * Public API, a single auto-detecting entry point consumed by the rest of
3
- * the application.
2
+ * A tiny, framework-agnostic SVG document model plus its serialisers.
4
3
  *
5
- * The conversion pipeline for both formats follows the same high-level steps:
6
- * 1. Parse the file header to determine logical bounds and canvas dimensions
4
+ * The SVG backend (`svg-context.ts`) records a metafile's drawing into an
5
+ * {@link SvgNode} tree rather than straight into markup, so the same result
6
+ * can be handed to whichever consumer needs it:
7
+ *
8
+ * - {@link svgTreeToString}: standalone SVG markup (`<svg xmlns=...>...</svg>`)
9
+ * - {@link svgTreeToDataUrl}: a `data:image/svg+xml;base64,...` URL, usable
10
+ * anywhere an image URL is (`<img src>`, CSS `background-image`, ...)
11
+ * - {@link svgTreeToReact}: live elements for React (or Preact, Solid's
12
+ * `h`, Vue's `h`, ...), built through a caller-supplied `createElement`,
13
+ * so this package never depends on a UI framework
14
+ * - {@link svgTreeToJsx}: JSX/TSX component source code, for build-time code
15
+ * generation in the style of SVGR
16
+ *
17
+ * Attribute names are stored in their SVG (kebab-case) spelling; the React
18
+ * and JSX serialisers convert them to the camelCase property names React
19
+ * expects (`stroke-width` → `strokeWidth`, `clip-path` → `clipPath`, and a
20
+ * `style` string becomes a style object).
21
+ *
22
+ * @module svg-tree
23
+ */
24
+ /** One SVG element. Text content (for `<text>`) lives in {@link SvgNode.text}. */
25
+ interface SvgNode {
26
+ /** Element name, e.g. `path`, `g`, `linearGradient`. */
27
+ tag: string;
28
+ /** Attributes in SVG spelling (`stroke-width`, `clip-path`, `style`). */
29
+ attrs: Record<string, string | number>;
30
+ /** Child elements, in paint order. */
31
+ children?: SvgNode[];
32
+ /** Character data for text-bearing elements. Mutually exclusive with children. */
33
+ text?: string;
34
+ }
35
+ /** Serialises a tree to SVG markup. The root should be an `<svg>` element. */
36
+ declare function svgTreeToString(node: SvgNode): string;
37
+ /** Serialises a tree to a base64 `data:image/svg+xml` URL. */
38
+ declare function svgTreeToDataUrl(node: SvgNode): string;
39
+ /**
40
+ * A `createElement`-compatible factory: `React.createElement`, Preact's `h`,
41
+ * and most hyperscript-style factories fit this shape.
42
+ */
43
+ type CreateElement<E> = (type: string, props: Record<string, unknown> | null, ...children: unknown[]) => E;
44
+ /**
45
+ * Builds live framework elements from a tree via `createElement`.
46
+ *
47
+ * ```tsx
48
+ * import { createElement } from 'react';
49
+ * const tree = await convertMetafileToSvgTree(buffer);
50
+ * return tree ? svgTreeToReact(tree, createElement, { className: 'figure', width: '100%' }) : null;
51
+ * ```
52
+ *
53
+ * @param node - The tree (normally the root `<svg>`).
54
+ * @param createElement - `React.createElement` or a compatible factory.
55
+ * @param rootProps - Extra props merged onto the root element (override
56
+ * `width`/`height`, add `className`, `role`, ...).
57
+ */
58
+ declare function svgTreeToReact<E>(node: SvgNode, createElement: CreateElement<E>, rootProps?: Record<string, unknown>): E;
59
+ /** Options for {@link svgTreeToJsx}. */
60
+ interface SvgJsxOptions {
61
+ /** Component name. Default `Metafile`. */
62
+ componentName?: string;
63
+ /** Emit TypeScript (`SVGProps<SVGSVGElement>` typing). Default `true`. */
64
+ typescript?: boolean;
65
+ /**
66
+ * Spread the component's props onto the root `<svg>` (after the recorded
67
+ * attributes, so callers can override `width`/`height`). Default `true`.
68
+ */
69
+ spreadProps?: boolean;
70
+ }
71
+ /**
72
+ * Generates JSX/TSX source for a React component rendering the tree, for
73
+ * build-time code generation (write it to a `.tsx` file and import it).
74
+ *
75
+ * ```ts
76
+ * const tree = await convertMetafileToSvgTree(buffer, { idPrefix: 'logo-' });
77
+ * writeFileSync('Logo.tsx', svgTreeToJsx(tree!, { componentName: 'Logo' }));
78
+ * ```
79
+ *
80
+ * The output uses the automatic JSX runtime (no `import React` needed); with
81
+ * `typescript: true` it imports only the `SVGProps` type from `react`.
82
+ */
83
+ declare function svgTreeToJsx(node: SvgNode, options?: SvgJsxOptions): string;
84
+
85
+ /**
86
+ * Public API: auto-detecting EMF/WMF conversion to PNG or SVG.
87
+ *
88
+ * The conversion pipeline for both formats and both outputs follows the same
89
+ * high-level steps:
90
+ * 1. Parse the file header to determine logical bounds and output dimensions
7
91
  * (tried as EMF first, then WMF, to auto-detect the format).
8
- * 2. Create an in-memory canvas (OffscreenCanvas preferred, HTMLCanvasElement
9
- * fallback, or the optional `@napi-rs/canvas` Node.js backend).
10
- * 3. Replay every metafile record onto the canvas context in order.
92
+ * 2. Create a drawing surface: an in-memory canvas (OffscreenCanvas
93
+ * preferred, HTMLCanvasElement fallback, or the optional `@napi-rs/canvas`
94
+ * Node.js backend) for PNG output, or an {@link SvgContext} recorder for
95
+ * SVG output.
96
+ * 3. Replay every metafile record onto the surface in order.
11
97
  * 4. Resolve "deferred images", bitmap / embedded-metafile draws that require
12
98
  * async image decoding (via {@link createImageBitmap} or, in Node.js, the
13
- * `@napi-rs/canvas` `loadImage` helper).
14
- * 5. Export the canvas contents as a `data:image/png;base64,...` URL.
99
+ * `@napi-rs/canvas` `loadImage` helper). SVG output embeds PNG/JPEG/GIF/
100
+ * WebP bytes verbatim and nested metafiles as nested SVG, with no decode.
101
+ * 5. Export: a `data:image/png;base64,...` URL, or an SVG tree that can be
102
+ * serialised to markup, a data URL, React elements, or JSX source.
15
103
  *
16
104
  * @module emf-converter
17
105
  */
106
+
18
107
  /**
19
108
  * Configuration options for EMF/WMF conversion.
20
109
  */
@@ -25,8 +114,8 @@ interface EmfConvertOptions {
25
114
  maxHeight?: number;
26
115
  /**
27
116
  * DPI scale factor for higher-resolution output.
28
- * Default is 2 (HiDPI). Set to 1 for 1:1 pixel mapping.
29
- * Values above 4 are clamped to 4 to prevent excessive memory usage.
117
+ * Default is 1 (1:1 pixel mapping). Values above 4 are clamped to 4 to
118
+ * prevent excessive memory usage.
30
119
  */
31
120
  dpiScale?: number;
32
121
  /**
@@ -46,6 +135,106 @@ interface EmfConvertOptions {
46
135
  * 'ms shell dlg': 'Tahoma' }`. Applied to GDI, WMF, and EMF+ text.
47
136
  */
48
137
  fontFamilyMap?: Record<string, string>;
138
+ /**
139
+ * Smooth shape edges instead of reproducing Windows' own rasterisation.
140
+ *
141
+ * PNG output defaults to `false`: plain-GDI vector shapes (Rectangle,
142
+ * Ellipse, RoundRect, Polygon, Polyline, arcs, bracketed paths, wide
143
+ * pens) are rasterised the way Windows GDI does, with its 28.4
144
+ * fixed-point geometry, fill rule, line algorithm and Bezier flattening,
145
+ * and EMF+ fills, strokes and clips follow the GDI+ `SmoothingMode` the
146
+ * file records (None, Default and HighSpeed aliased on GDI+'s pixel grid,
147
+ * AntiAlias and HighQuality with GDI+'s 8 x 4-sample antialiasing), so the
148
+ * PNG matches what Windows paints pixel for pixel.
149
+ *
150
+ * `true` draws every edge with Canvas's own antialiasing instead (still
151
+ * with GDI's geometry, pen widths, caps, joins and dash patterns), which
152
+ * looks smoother than Windows, especially for files recorded without
153
+ * GDI+ antialiasing.
154
+ *
155
+ * SVG output defaults to smooth vector edges (an SVG is meant to scale);
156
+ * `false` there embeds Windows' aliased shape pixels as image patches.
157
+ */
158
+ gdiAntialias?: boolean;
159
+ /**
160
+ * Font files to render GDI and WMF text with, exactly as Windows GDI
161
+ * does: TrueType `.ttf` / `.ttc` and raster `.fon` / `.fnt` bytes
162
+ * (`loadSystemFonts()` reads the installed ones in Node.js). The
163
+ * LOGFONT is realised against these files (face, weight, slant,
164
+ * `lfHeight`/`lfWidth`, charset fallback), each TrueType glyph is grid-fitted by the font's own TrueType
165
+ * instructions and scan-converted with TrueType dropout control
166
+ * (non-antialiased, 4x4 grayscale or ClearType per the LOGFONT's
167
+ * `lfQuality`), and glyphs are placed on GDI's integer device grid with
168
+ * GDI's own advance widths, cell metrics, underline and strike-out.
169
+ * Raster faces (MS Sans Serif, Helv, System, Terminal, ...) are drawn
170
+ * from their bitmaps at the size and whole-number stretch GDI picks.
171
+ * Supply the fonts the metafile names (for Windows-authored files, the
172
+ * matching files from `C:\Windows\Fonts`); a face that is missing is
173
+ * substituted the way GDI's font mapper would (by pitch and family),
174
+ * and without this option text is drawn with the canvas font engine.
175
+ * Ignored by SVG output, which keeps text as `<text>` but takes its
176
+ * per-glyph positions and metrics from these fonts.
177
+ */
178
+ fonts?: Array<ArrayBuffer | ArrayBufferView>;
179
+ /**
180
+ * Windows' system-wide font smoothing, which GDI applies to fonts that
181
+ * ask for `DEFAULT_QUALITY`, `DRAFT_QUALITY` or `PROOF_QUALITY` (most
182
+ * metafiles): `'cleartype'` (Windows' default), `'gray'` (standard
183
+ * antialiasing) or `'mono'` (smoothing off). Only used with `fonts`.
184
+ */
185
+ fontSmoothing?: 'cleartype' | 'gray' | 'mono';
186
+ }
187
+ /**
188
+ * Options for the SVG outputs ({@link convertMetafileToSvg} and friends).
189
+ * `maxWidth`/`maxHeight`/`dpiScale`/`maxCanvasDimension` set the SVG's
190
+ * coordinate space (its `viewBox` and default `width`/`height`) and the
191
+ * resolution of any embedded raster content; vector content stays sharp at
192
+ * any display size.
193
+ */
194
+ interface SvgConvertOptions extends EmfConvertOptions {
195
+ /**
196
+ * Evaluate raster operations that read the destination (exact ROP3 blits,
197
+ * bitwise ROP2, pattern-brush fills combined through ROP2, and
198
+ * `gdiAntialias: false` shapes) against a hidden raster mirror of the
199
+ * drawing, and embed the pixels they change as image patches. The mirror
200
+ * is the canvas backend when one exists (browser/worker canvas, or
201
+ * `@napi-rs/canvas` in Node.js) and the built-in pure-JavaScript
202
+ * rasteriser otherwise, so this needs no canvas. The built-in mirror
203
+ * cannot draw glyphs: where a raster operation reads pixels under text,
204
+ * every pixel whose result does not depend on the glyphs stays exact and
205
+ * the rest is handed to the SVG renderer as a blend-mode layer (exact for
206
+ * inversion and for masks whose channels are all 0 or 255). With `false`,
207
+ * no mirror is kept and those operations fall back to SVG blend modes
208
+ * (`mix-blend-mode`), which are exact for the common mask ROPs on
209
+ * black/white masks and approximate otherwise. Default `true`.
210
+ */
211
+ exactRasterOps?: boolean;
212
+ /**
213
+ * How EMF+ `DrawImage` bitmaps are scaled. `'renderer'` (the default)
214
+ * embeds the original image and lets the SVG renderer scale it with its
215
+ * own smoothing, which stays sharp at any display size. `'exact'` bakes
216
+ * each draw at device resolution with the GDI+-matching resampler (the
217
+ * PNG output's `InterpolationMode`/`PixelOffsetMode` model), so the SVG
218
+ * shows what GDI+ painted pixel for pixel at its nominal size. PNG and
219
+ * BMP images are decoded in pure JavaScript; JPEG, GIF and other formats
220
+ * need a canvas backend to decode and otherwise keep `'renderer'`
221
+ * scaling, as do draws GDI+ scales with a filter the resampler does not
222
+ * model (bicubic, high-quality).
223
+ */
224
+ imageResampling?: 'renderer' | 'exact';
225
+ /**
226
+ * Emit `width`/`height` attributes on the root `<svg>` (the `viewBox` is
227
+ * always emitted). Set `false` for a fluid SVG that fills its container.
228
+ * Default `true`.
229
+ */
230
+ includeSize?: boolean;
231
+ /**
232
+ * Prefix for every generated element id (clip paths, gradients,
233
+ * patterns). Ids must be unique within an HTML document, so give each
234
+ * inlined SVG its own prefix. Defaults to a per-process counter
235
+ * (`emf1-`, `emf2-`, ...).
236
+ */
237
+ idPrefix?: string;
49
238
  }
50
239
  /**
51
240
  * Converts an EMF (Enhanced Metafile) or WMF (Windows Metafile) binary buffer
@@ -56,23 +245,17 @@ interface EmfConvertOptions {
56
245
  * starts with a valid `EMR_HEADER` record, so it doubles as a safe format
57
246
  * sniff. When that probe fails, the buffer is parsed as WMF instead.
58
247
  *
59
- * For EMF: parses the EMF header, iterates over all EMR records, and replays
60
- * them onto an in-memory canvas. Embedded EMF+ (GDI+) records found inside
61
- * EMR_COMMENT payloads are handled transparently.
62
- *
63
- * For WMF: parses the optional Aldus placeable header and the standard WMF
64
- * header, then replays all META_* records onto a canvas.
65
- *
66
- * The canvas is rendered at a configurable DPI scale (default 1x, 1:1 pixel
67
- * mapping) via {@link EmfConvertOptions.dpiScale}. On the first call in a
68
- * given process, the optional Node.js canvas backend (`@napi-rs/canvas`) is
69
- * loaded once and cached; see {@link ensureNodeCanvasModule}.
70
- *
71
248
  * Returns `null` when:
72
249
  * - The buffer matches neither a valid EMF header nor a valid WMF header.
73
250
  * - The logical bounds are zero-sized or negative.
74
251
  * - No canvas API is available (browser/worker canvas, or the optional
75
- * `@napi-rs/canvas` package in plain Node.js).
252
+ * `@napi-rs/canvas` package in plain Node.js) AND the drawing contains
253
+ * text or an image format only a canvas can decode (JPEG, GIF, ...).
254
+ * Without a canvas the built-in pure-JavaScript rasteriser renders
255
+ * everything else (vectors, clipping, gradients, bitmaps, PNG/BMP
256
+ * images, every raster operation), but it has no font engine, so rather
257
+ * than return an image silently missing its text it returns `null`. SVG
258
+ * output ({@link convertMetafileToSvg}) needs no canvas at all.
76
259
  *
77
260
  * @param buffer - The raw EMF or WMF file bytes.
78
261
  * @param options - Optional {@link EmfConvertOptions} controlling output size,
@@ -82,6 +265,38 @@ interface EmfConvertOptions {
82
265
  */
83
266
  declare function convertMetafileToDataUrl(buffer: ArrayBuffer, options?: EmfConvertOptions, recursionDepth?: number): Promise<string | null>;
84
267
 
268
+ /**
269
+ * Converts an EMF or WMF buffer (format auto-detected) into an SVG document
270
+ * tree, the common source for every SVG output form: serialise it with
271
+ * {@link svgTreeToString} / {@link svgTreeToDataUrl}, render it in React
272
+ * with {@link svgTreeToReact}, or generate component source with
273
+ * {@link svgTreeToJsx}.
274
+ *
275
+ * This needs no canvas implementation: vectors, text, gradients, clipping,
276
+ * and bitmaps are all recorded in pure JavaScript, and destination-reading
277
+ * raster operations are evaluated exactly against a raster mirror of the
278
+ * drawing (see {@link SvgConvertOptions.exactRasterOps}), which is the
279
+ * canvas backend when one exists (it also measures text) and the built-in
280
+ * pure-JavaScript rasteriser otherwise.
281
+ *
282
+ * @returns The root `<svg>` node, or `null` for an invalid/empty metafile.
283
+ */
284
+ declare function convertMetafileToSvgTree(buffer: ArrayBuffer, options?: SvgConvertOptions, recursionDepth?: number): Promise<SvgNode | null>;
285
+ /**
286
+ * Converts an EMF or WMF buffer into standalone SVG markup
287
+ * (`<svg xmlns="http://www.w3.org/2000/svg" ...>...</svg>`).
288
+ *
289
+ * @returns The SVG markup, or `null` for an invalid/empty metafile.
290
+ */
291
+ declare function convertMetafileToSvg(buffer: ArrayBuffer, options?: SvgConvertOptions): Promise<string | null>;
292
+ /**
293
+ * Converts an EMF or WMF buffer into a base64 SVG data URL
294
+ * (`data:image/svg+xml;base64,...`), usable directly as an `<img src>`.
295
+ *
296
+ * @returns The data URL, or `null` for an invalid/empty metafile.
297
+ */
298
+ declare function convertMetafileToSvgDataUrl(buffer: ArrayBuffer, options?: SvgConvertOptions): Promise<string | null>;
299
+
85
300
  /**
86
301
  * The default DPI scale factor used for EMF/WMF rendering.
87
302
  * Set to 1 for 1:1 pixel mapping (default).
@@ -89,4 +304,54 @@ declare function convertMetafileToDataUrl(buffer: ArrayBuffer, options?: EmfConv
89
304
  */
90
305
  declare const DEFAULT_DPI_SCALE = 1;
91
306
 
92
- export { DEFAULT_DPI_SCALE, type EmfConvertOptions, convertMetafileToDataUrl };
307
+ /**
308
+ * `loadSystemFonts()`: reads the operating system's installed font files
309
+ * (Node.js only) into buffers for the converter's `fonts` option.
310
+ *
311
+ * The Node.js modules are loaded with dynamic `import()` (and bundler
312
+ * ignore comments) only when the function is called, so the package stays
313
+ * browser-safe: nothing here is resolved or bundled for a browser build.
314
+ *
315
+ * @module load-system-fonts
316
+ */
317
+ /** Options for {@link loadSystemFonts}. */
318
+ interface LoadSystemFontsOptions {
319
+ /**
320
+ * Directories to scan instead of the platform defaults (Windows:
321
+ * `%WINDIR%\Fonts` and the per-user `%LOCALAPPDATA%\Microsoft\Windows\Fonts`;
322
+ * Linux: `/usr/share/fonts`, `/usr/local/share/fonts`, `~/.fonts`,
323
+ * `~/.local/share/fonts`; macOS: `/Library/Fonts`,
324
+ * `/System/Library/Fonts`, `~/Library/Fonts`). Missing directories are
325
+ * skipped.
326
+ */
327
+ dirs?: string[];
328
+ /**
329
+ * Keeps only the files this returns true for, given the full path and
330
+ * the lower-case file name (for example to load just the faces a
331
+ * metafile names: `(p, n) => /^(arial|times|cour)/.test(n)`).
332
+ */
333
+ filter?: (path: string, name: string) => boolean;
334
+ /** Subdirectory depth to descend (default 4; 0 scans only the directories themselves). */
335
+ maxDepth?: number;
336
+ }
337
+ /**
338
+ * Reads the installed TrueType (`.ttf`, `.ttc`) and raster (`.fon`,
339
+ * `.fnt`) font files, for `convertMetafileToDataUrl(data, { fonts })`
340
+ * and the SVG converters. Node.js only: in a browser (or any runtime
341
+ * without `process.versions.node`) it resolves to an empty array.
342
+ *
343
+ * Reading every installed font can take a few hundred megabytes on
344
+ * Windows; pass `filter` to load only what your metafiles use. Load once
345
+ * and reuse the array across conversions.
346
+ *
347
+ * @example
348
+ * ```ts
349
+ * import { convertMetafileToDataUrl, loadSystemFonts } from 'emf-converter';
350
+ *
351
+ * const fonts = await loadSystemFonts();
352
+ * const png = await convertMetafileToDataUrl(emfBytes, { fonts });
353
+ * ```
354
+ */
355
+ declare function loadSystemFonts(options?: LoadSystemFontsOptions): Promise<Uint8Array[]>;
356
+
357
+ export { type CreateElement, DEFAULT_DPI_SCALE, type EmfConvertOptions, type LoadSystemFontsOptions, type SvgConvertOptions, type SvgJsxOptions, type SvgNode, convertMetafileToDataUrl, convertMetafileToSvg, convertMetafileToSvgDataUrl, convertMetafileToSvgTree, loadSystemFonts, svgTreeToDataUrl, svgTreeToJsx, svgTreeToReact, svgTreeToString };