Skip to content

Repository files navigation

emf-converter

npm version CI license

A zero-dependency TypeScript library that converts EMF (Enhanced Metafile, including embedded EMF+ / GDI+ records) and WMF (Windows Metafile) files into PNG or SVG (markup, a base64 data URL, React elements, or a generated JSX/TSX component).

Windows metafiles are recorded GDI and GDI+ drawing calls, commonly embedded in Office documents and on the Windows clipboard. This library replays those calls the way Windows does: the PNG output is checked pixel for pixel against images painted by Windows itself (hundreds of ground-truth fixtures under src/__fixtures__/gdi, generated by scripts/gdi-fixtures), and the SVG output keeps vectors, text and gradients resolution-independent.

Format Description Coordinate system
WMF Windows Metafile (16-bit) Window/viewport mapping
EMF Enhanced Metafile (32-bit GDI) Bounds-based scaling
EMF+ GDI+ extension embedded in EMF World transform matrix

▶️ Live demo · 📦 npm


What's new

  • SVG output: convertMetafileToSvg, convertMetafileToSvgDataUrl, convertMetafileToSvgTree + svgTreeToReact / svgTreeToJsx for JSX/TSX.
  • Windows-exact PNG by default: GDI shapes are drawn by a rasteriser fitted to Windows GDI (28.4 fixed-point geometry, GDI's fill rule, line algorithm, ellipse and Bezier construction, wide pens, dash styles), and EMF+ drawing follows the file's recorded GDI+ SmoothingMode with GDI+'s own rasteriser. Breaking: default PNG output is no longer Canvas-antialiased; pass gdiAntialias: true for the previous smooth edges.
  • Exact text with the fonts option: a built-in TrueType engine (hinting interpreter, dropout control, GDI font mapping and metrics, grayscale and ClearType) plus Windows raster .fon fonts. loadSystemFonts() reads the installed fonts in Node.js.
  • No canvas required: a built-in pure-JavaScript rasteriser renders SVG anywhere and PNG for drawings without text; @napi-rs/canvas is only needed for PNG output with text in plain Node.js.
  • Complete WMF playback: bitmaps, clipping, regions, mapping modes, palettes, flood fills, and embedded EMF comments, played as Windows' PlayMetaFile plays them.
  • Many correctness fixes found by the new fixtures (see the changelog).

Demo

Drop an .emf or .wmf file into the browser demo to see the PNG or SVG output, download it, or copy it as a TSX component:

https://christophervr.github.io/emf-converter/

Install

npm install emf-converter

No required dependencies:

  • Browser / Web Worker: OffscreenCanvas or HTMLCanvasElement is used automatically.

  • Node.js: SVG output, and PNG output for drawings without text, work out of the box through the built-in rasteriser. For PNG output of drawings with text, either pass fonts (see Exact text) or install the optional @napi-rs/canvas (prebuilt, no node-gyp):

    npm install @napi-rs/canvas

    Without either, PNG conversion of a drawing that contains text returns null rather than an image missing its text.

Quick start

import { convertMetafileToDataUrl } from 'emf-converter';

const buffer: ArrayBuffer = /* an .emf or .wmf file */;
const png = await convertMetafileToDataUrl(buffer);
// => "data:image/png;base64,iVBORw0KGgo..."  (the format is auto-detected)

// Limit the output size (aspect ratio preserved), or render at 2x.
const thumb = await convertMetafileToDataUrl(buffer, { maxWidth: 1024, maxHeight: 768 });
const hiDpi = await convertMetafileToDataUrl(buffer, { dpiScale: 2 });

// Smooth (Canvas-antialiased) edges instead of Windows' own rasterisation.
const smooth = await convertMetafileToDataUrl(buffer, { gdiAntialias: true });

Returns Promise<string | null>; null when the buffer is not a valid metafile (or, in plain Node.js, when it has text and neither fonts nor @napi-rs/canvas is available).

SVG output

import { convertMetafileToSvg, convertMetafileToSvgDataUrl } from 'emf-converter';

const markup = await convertMetafileToSvg(buffer);
// => '<svg xmlns="http://www.w3.org/2000/svg" width="..." height="..." viewBox="...">...</svg>'

const svgUrl = await convertMetafileToSvgDataUrl(buffer);
// => "data:image/svg+xml;base64,PHN2ZyB4bWxucz0i..."  (drop straight into <img src>)

Paths, text, gradients, clipping and pattern brushes stay vectors; bitmaps are embedded as <image> elements (PNG/JPEG/GIF/WebP bytes verbatim, never re-encoded). Raster operations that read the destination (all 256 ROP3 codes, bitwise ROP2, pattern brushes through ROP2) are evaluated exactly against a hidden raster mirror and embedded as image patches holding only the pixels they change, so the SVG is the same with or without a canvas backend.

Rendering in React (JSX / TSX)

convertMetafileToSvgTree returns a plain SvgNode tree. Turn it into live elements with any createElement-style factory (React, Preact, ...), so the SVG is part of your component tree and can be styled, sized and given props like any other element:

import { createElement, useEffect, useState, type ReactNode } from 'react';
import { convertMetafileToSvgTree, svgTreeToReact } from 'emf-converter';

export function Metafile({ buffer }: { buffer: ArrayBuffer }) {
	const [svg, setSvg] = useState<ReactNode>(null);
	useEffect(() => {
		let live = true;
		convertMetafileToSvgTree(buffer).then((tree) => {
			if (live && tree) {
				// Extra props land on the root <svg>: override size, add a class, aria, ...
				setSvg(svgTreeToReact(tree, createElement, { width: '100%', height: 'auto', role: 'img' }));
			}
		});
		return () => {
			live = false;
		};
	}, [buffer]);
	return svg;
}

Or generate a component at build time (the SVGR approach):

import { writeFileSync } from 'node:fs';
import { convertMetafileToSvgTree, svgTreeToJsx } from 'emf-converter';

const tree = await convertMetafileToSvgTree(buffer, { idPrefix: 'logo-' });
writeFileSync('Logo.tsx', svgTreeToJsx(tree!, { componentName: 'Logo' }));
// export function Logo(props: SVGProps<SVGSVGElement>) { return (<svg ... {...props}> ... </svg>); }

Attribute names are converted to React's spelling (stroke-width → strokeWidth, clip-path → clipPath, style strings → style objects). Strings that come from the metafile (font names, text) are always emitted as escaped JavaScript string literals in generated source, never spliced into JSX raw. When several converted SVGs are inlined in one page, give each its own idPrefix so their clip-path and gradient ids cannot collide (a unique prefix per conversion is the default).

Exact text

Text is only as exact as the fonts it is drawn with. Pass the font files the metafile uses as fonts (TrueType .ttf/.ttc and Windows raster .fon/.fnt), and text is drawn the way Windows GDI draws it:

import { convertMetafileToDataUrl, loadSystemFonts } from 'emf-converter';

const fonts = await loadSystemFonts(); // Node.js only; reuse the array across conversions
const png = await convertMetafileToDataUrl(buffer, { fonts });
  • Fonts are realised the way GDI's font mapper does it (face substitutes, pitch/family fallback, weight choice, cell vs em height, lfWidth stretching), with GDI's metrics, advances, underline and strike-out.
  • Glyphs are grid-fitted by the font's own TrueType instructions (including Windows' ClearType rules), scan-converted with dropout control, and placed on GDI's integer grid honouring Dx arrays, ETO_* flags and every TA_* alignment.
  • Non-antialiased, grayscale or ClearType rendering is chosen from the font's quality; fontSmoothing sets what DEFAULT_QUALITY means (Windows' default is ClearType).
  • Raster faces (MS Sans Serif, MS Serif, Courier, Small Fonts, System, Terminal, Fixedsys, Helv, Tms Rmn) are drawn from their bitmaps with GDI's size choice and stretching.
  • Rotated text uses GDI's rounded font matrix; EMF+ DrawString honours the text rendering hint, string-format tracking and margins, and texture/gradient brushes.

Without fonts, text is drawn by the host's canvas font engine (supply fontFamilyMap to remap Windows face names). SVG output always keeps text as <text>; with fonts it carries GDI's exact per-glyph positions.

API

convertMetafileToDataUrl(buffer, options?)

Parameter Type Description
buffer ArrayBuffer Raw EMF or WMF file bytes (format is auto-detected)
options EmfConvertOptions (optional) See below
Returns Promise<string | null> PNG data URL, or null on failure

EmfConvertOptions

Field Type Default Description
maxWidth number None Maximum output width in pixels (aspect ratio preserved)
maxHeight number None Maximum output height in pixels
dpiScale number 1 Resolution multiplier; clamped to 4
maxCanvasDimension number 8192 Hard cap on output width/height in pixels
maxRecords number 200000/500000 Records processed per stream before replay stops (EMF+ uses the higher default unless overridden)
gdiAntialias boolean false (PNG) true smooths every shape edge with Canvas antialiasing instead of reproducing Windows' own GDI/GDI+ rasterisation
fonts Array<ArrayBuffer | ArrayBufferView> None TrueType (.ttf/.ttc) and raster (.fon/.fnt) font files for exact GDI text
fontSmoothing 'cleartype' | 'gray' | 'mono' 'cleartype' What DEFAULT_QUALITY / DRAFT_QUALITY / PROOF_QUALITY fonts render as (Windows' system setting)
fontFamilyMap Record<string, string> None Without fonts: maps Windows face names (case-insensitive) to locally available fonts, e.g. { calibri: 'Carlito' }

SVG functions

Function Returns
convertMetafileToSvg(buffer, options?) Promise<string | null>, standalone SVG markup
convertMetafileToSvgDataUrl(buffer, options?) Promise<string | null>, a data:image/svg+xml;base64,... URL
convertMetafileToSvgTree(buffer, options?) Promise<SvgNode | null>, the tree the helpers below consume
svgTreeToString(tree) / svgTreeToDataUrl(tree) Markup / base64 data URL for an existing tree
svgTreeToReact(tree, createElement, rootProps?) Live elements via React.createElement (or any compatible factory)
svgTreeToJsx(tree, { componentName?, typescript?, spreadProps? }) JSX/TSX component source code

SvgConvertOptions (extends EmfConvertOptions)

Field Type Default Description
gdiAntialias boolean true (SVG) false embeds Windows' aliased GDI shape pixels as image patches instead of smooth vector edges
exactRasterOps boolean true false skips the raster mirror and expresses destination-reading raster ops with SVG mix-blend-mode equivalents
imageResampling 'renderer' | 'exact' 'renderer' 'exact' bakes EMF+ DrawImage at device resolution with GDI+'s resampling kernel instead of letting the SVG renderer scale the original image
includeSize boolean true Emit width/height on the root <svg> (viewBox is always emitted); false gives a fluid SVG
idPrefix string emf1-, emf2-, ... Prefix for generated element ids; keep it unique per inlined SVG

loadSystemFonts(options?)

Node.js only (returns [] elsewhere; the package stays browser-safe). Reads the installed .ttf, .ttc, .fon and .fnt files from the platform font folders (Windows, Linux, macOS, and per-user folders) for the fonts option. Options: dirs (scan these instead), filter(path, name), maxDepth.

How it works

A three-phase pipeline: parse → replay → export. The header parser reads the drawing bounds (a placeable WMF is sized from its header's units per inch), the output surface is created (clamped to maxCanvasDimension), and the records are replayed in order by the GDI, EMF+ or WMF handlers. PNG output draws onto a Canvas (OffscreenCanvas, HTMLCanvasElement, @napi-rs/canvas, or the built-in pure-JavaScript rasteriser); SVG output draws onto SvgContext, a recorder implementing the part of the Canvas 2D API the replay uses, mirrored onto a hidden raster wherever a raster operation must read the destination.

Everything below is verified against output painted by Windows itself; src/gdi-parity.fixture.test.ts holds the per-fixture bounds.

  • GDI shapes (gdi-raster.ts, gdi-raster-widen.ts): 28.4 fixed-point geometry; GDI's fill rule (ALTERNATE/WINDING); one-pixel lines by GDI's diamond rule with its tie-breaks; GDI's own Bezier flattener, ellipse, rounded-rectangle, arc (GDI's trigonometry table and SetArcDirection), chord and pie construction; cosmetic dash styles (dash 18/6, dot 3/3, ...) and geometric dashes; wide pens widened from GDI's own pen polygons with every cap and join and the miter limit; rotated and skewed world transforms. Pixel-exact on the shape fixtures.
  • Raster operations: all 256 ROP3 codes for BitBlt/StretchBlt/StretchDIBits/PatBlt, exact per bit against the destination, brush and source, with GDI's stretch modes, mirrored rectangles and rotated destinations (each device pixel mapped back to one source texel). Every SetROP2 mode, including the bitwise AND/OR/XOR family, for shapes, paths and pattern-brush fills.
  • Brushes: hatch, monochrome and DIB pattern brushes anchored to the brush origin, with the background mode; GDI+ solid, hatch, texture (bilinear, WrapMode-aware, as GDI+ samples them), linear gradients (GDI+'s own interpolation table: preset colours, blend shapes, gamma correction, every WrapMode) and path gradients (true boundary-shaped falloff, every WrapMode).
  • Clipping: every GDI and GDI+ region combine mode exact for every clip (vector where possible, otherwise scan-converted to pixel regions, which is how GDI stores them), path clips with their fill mode, and region offsets.
  • EMF+: fills, pens and clips follow the recorded SmoothingMode with GDI+'s own fill rasteriser (8 x 4-sample antialiasing, blend arithmetic) and pen widener (joins, caps, dash caps, compound lines, inset alignment); DrawImage with every InterpolationMode/PixelOffsetMode kernel, ImageAttributes wrap modes, drawn in record order under the live clip; embedded metafiles replayed as vectors; continuation records reassembled; compressed textures and images decoded before replay.
  • Text: see Exact text.
  • WMF: played as PlayMetaFile plays it (GM_COMPATIBLE whole-pixel rules, mapping modes, bitmaps, pattern brushes, clipping and regions, palettes, flood fills, text spacing and justification, right-to-left layout); an EMF embedded in MFCOMMENT escapes is played instead, as Windows does.

Supported records

  • EMF: 115 of the 119 record types defined in MS-EMF, including logical palettes (PALETTEINDEX, DIBPALETTEINDEX, PALETTERGB, DIB_PAL_COLORS), EMR_ALPHABLEND (Windows' exact integer blend), EMR_TRANSPARENTBLT, EMR_MASKBLT, EMR_PLGBLT, EMR_SETDIBITSTODEVICE, EMR_GRADIENTFILL (rectangles and triangles), EMR_FILLRGN / EMR_FRAMERGN / EMR_INVERTRGN / EMR_PAINTRGN, EMR_EXTFLOODFILL, EMR_ANGLEARC, EMR_POLYDRAW(16), EMR_FLATTENPATH / EMR_WIDENPATH / EMR_ABORTPATH, alongside shapes, paths, EMR_EXTTEXTOUTW, blits, clipping and transforms. Colour space, ICM, OpenGL, escape and font-driver records are consumed without effect, as on a Windows display.
  • EMF+: every record in MS-EMFPLUS (Beziers, cardinal curves, regions, containers, save/restore, compositing mode, rendering origin, text contrast, StrokeFillPath, the terminal-server SetTSGraphics / SetTSClip, MultiFormat* played as GDI+ plays them), with 32-bit, compressed 16-bit and relative point data, and every object type (solid, hatch, texture and gradient brushes; pens with caps, joins, dash styles, dash caps, compound lines and custom line caps; paths, regions, bitmap and metafile images, fonts, string formats, image attributes). Several encodings follow what GDI+ actually does where it differs from MS-EMFPLUS (relative points, StrokeFillPath, SetTSGraphics, SetTSClip).
  • WMF: META_ANIMATEPALETTE, META_ARC, META_BITBLT, META_CHORD, META_CREATEBITMAP, META_CREATEBITMAPINDIRECT, META_CREATEBRUSH, META_CREATEBRUSHINDIRECT, META_CREATEFONTINDIRECT, META_CREATEPALETTE, META_CREATEPATTERNBRUSH, META_CREATEPENINDIRECT, META_CREATEREGION, META_DELETEOBJECT, META_DIBBITBLT, META_DIBCREATEPATTERNBRUSH, META_DIBSTRETCHBLT, META_ELLIPSE, META_EOF, META_ESCAPE, META_EXCLUDECLIPRECT, META_EXTFLOODFILL, META_EXTTEXTOUT, META_FILLREGION, META_FLOODFILL, META_FRAMEREGION, META_INTERSECTCLIPRECT, META_INVERTREGION, META_LINETO, META_MOVETO, META_OFFSETCLIPRGN, META_OFFSETVIEWPORTORG, META_OFFSETWINDOWORG, META_PAINTREGION, META_PATBLT, META_PIE, META_POLYGON, META_POLYLINE, META_POLYPOLYGON, META_REALIZEPALETTE, META_RECTANGLE, META_RESIZEPALETTE, META_RESTOREDC, META_ROUNDRECT, META_SAVEDC, META_SCALEVIEWPORTEXT, META_SCALEWINDOWEXT, META_SELECTCLIPREGION, META_SELECTOBJECT, META_SELECTPALETTE, META_SETBKCOLOR, META_SETBKMODE, META_SETDIBTODEV, META_SETLAYOUT, META_SETMAPMODE, META_SETMAPPERFLAGS, META_SETPALENTRIES, META_SETPIXEL, META_SETPOLYFILLMODE, META_SETRELABS, META_SETROP2, META_SETSTRETCHBLTMODE, META_SETTEXTALIGN, META_SETTEXTCHAREXTRA, META_SETTEXTCOLOR, META_SETTEXTJUSTIFICATION, META_SETVIEWPORTEXT, META_SETVIEWPORTORG, META_SETWINDOWEXT, META_SETWINDOWORG, META_STRETCHBLT, META_STRETCHDIB, META_TEXTOUT. Where Windows no longer plays a record the way MS-WMF describes it (Win16 device bitmaps in META_BITBLT / META_STRETCHBLT, META_CREATEPATTERNBRUSH, banded META_SETDIBTODEV), the converter follows Windows.

Limitations

Everything is measured against output painted by Windows itself; src/gdi-parity.fixture.test.ts holds the exact per-fixture bounds.

  • Unhandled records: EMR_EXTTEXTOUTA, EMR_POLYTEXTOUTA, EMR_POLYTEXTOUTW and EMR_SMALLTEXTOUT (ANSI, multi-string and small-glyph text records, rarely written by modern recorders) are skipped with a console warning. EMR_SETTEXTJUSTIFICATION and EMR_SETCOLORADJUSTMENT are read but not yet applied (Windows' own recorder bakes justification into EMR_EXTTEXTOUTW spacing arrays, so only other writers emit the former), and the HALFTONE stretch mode is not bit-exact. EMF+ image effects (SerializableObject: blur, sharpen, colour matrix and the like) are not applied, so the image is drawn without the effect, and an EMF+ pen's own transform is ignored.
  • Wide pens and paths: flat-capped GDI pens 7 px and wider can differ by a few pixels at round joins, and dashed wide Bezier curves follow WidenPath (which Windows' direct drawing does not quite match); at most 0.2% of pixels on the fixtures. EMR_WIDENPATH does not reproduce the extra inner join triangles GDI's own WidenPath emits (visible only when the widened outline is itself stroked). EMF+ 1-pixel antialiased lines can differ by one antialiasing sample at their ends, some closed widened outlines by one sample along an edge, and Inset or compound pens on closed figures are approximate.
  • GM_COMPATIBLE recordings: EMF files do not record the graphics mode, and Windows plays RoundRect, Arc, Chord, Pie and null-pen Ellipse records back differently from how a GM_COMPATIBLE application drew them on screen; the converter follows Windows' playback.
  • Small EMF+ residuals: rotated HighQualityBicubic DrawImage edge pixels (0.14%), one-level differences at exact half-level Blend knots, and a few pixels of a metafile nested in DrawImage under a scale.
  • WMF: PS_INSIDEFRAME boxes can come out a pixel short at non-integer scales, right-to-left (LAYOUT_RTL) layouts differ by single pixels on mirrored diagonals, and metric map modes assume a 96 dpi reference device (Windows derives them from the physical display, so its own output varies per machine).

License

Apache-2.0, free for commercial and closed-source use, with an explicit patent grant.

About

A zero-dependency TypeScript library that converts EMF (Enhanced Metafile) and WMF (Windows Metafile) binary buffers into PNG data URLs by parsing their record streams and replaying drawing commands onto an HTML Canvas.

Resources

Stars

8 stars

Watchers

0 watching

Forks

Releases

Used by

Contributors

Languages