@s8fy/emf2svg
v1.3.5
Published
TypeScript EMF and WMF to SVG converter for browsers and Node.js, with zero runtime dependencies
Readme
@s8fy/emf2svg
API · Viewer documentation · Commercial licensing · Report an issue
Pure TypeScript EMF (Enhanced Metafile) and WMF (Windows Metafile) to SVG converter. It has zero runtime dependencies and runs in browsers and Node.js.
The package declares Node.js 22.12+, provides ESM/CommonJS TypeScript declarations, and needs no DOM for conversion. All five exported functions are synchronous.
Key Features
- Office metafiles rendered as SVG. Convert supported EMF and WMF drawings used by Office clip art, chart/object previews, and legacy equation fallbacks into SVG without Office automation or a browser DOM.
- Vector geometry and GDI state. The EMF path handles supported lines, polygons, Bézier curves, rectangles, ellipses, and arcs, with pens/brushes, coordinate transforms, and device-context save/restore. Supported EMF clipping and gradient records produce SVG output. WMF has a smaller record subset; the listed EMF operations are not all available for WMF.
- Text placement for legacy Office content. Consume supported font selection, alignment, character advances, and text colors. WMF decoding handles supported DBCS charsets; Symbol/MT Extra mappings and supported scalable delimiter paths preserve legacy equation glyphs.
- Canvas and object-frame compatibility. Preserve supported physical frames, window/viewport mapping, blank margins, and Office embedded-object canvas bounds so fallback graphics keep their intended placement rather than fitting only the visible ink.
- Embedded bitmap handling. Supported EMF DIB and bitmap records can coexist with vector output, including alpha blending. Transparent color keys and some bitmap operations are not applied; see Limitations. The result may contain raster image resources; conversion does not make embedded bitmaps into vectors.
- A small integration surface. Four synchronous functions provide EMF/WMF format probes and conversion, and a fifth encodes RGBA pixels as PNG. Zero runtime dependencies, browser/Node.js support, ESM/CommonJS/UMD builds, and TypeScript declarations.
This is a supported GDI record subset, not a full Windows graphics emulator. EMF+ (GDI+) drawing records and unsupported EMF/WMF operations are skipped, so output can be partial. Header probes do not validate every record, and malformed files can still fail conversion. This package converts metafile bytes, not entire PPTX files or live embedded applications.
When to use this package
Use @s8fy/emf2svg when you already have EMF or WMF bytes and need an SVG string in a browser or Node.js. It handles a subset of metafile drawing records and does not open entire PowerPoint files.
To extract supported metafile graphics from PPTX, use Parser. To preview the presentation, use Viewer; for standalone PDF/Markdown conversion, use Converter.
Install
npm install @s8fy/emf2svg
# or
pnpm add @s8fy/emf2svgUsage
Basic conversion
import { emf2svg, isEmf, isWmf, wmf2svg } from '@s8fy/emf2svg'
export function convertMetafile(buffer: ArrayBuffer | Uint8Array): string {
if (isEmf(buffer)) return emf2svg(buffer)
if (isWmf(buffer)) return wmf2svg(buffer)
throw new Error('Unsupported metafile header')
}Node.js
import { readFileSync, writeFileSync } from 'node:fs'
import { emf2svg } from '@s8fy/emf2svg'
const emfData = readFileSync('diagram.emf')
const svg = emf2svg(emfData)
writeFileSync('diagram.svg', svg)Browser (fetch)
import { emf2svg } from '@s8fy/emf2svg'
const res = await fetch('/assets/chart.emf')
if (!res.ok) throw new Error(`Metafile request failed: ${res.status}`)
const buffer = await res.arrayBuffer()
const svg = emf2svg(buffer)
const image = document.createElement('img')
image.alt = 'Converted chart'
const url = URL.createObjectURL(new Blob([svg], { type: 'image/svg+xml' }))
image.onload = image.onerror = () => URL.revokeObjectURL(url)
image.src = url
document.body.append(image)API
emf2svg(buffer: ArrayBuffer | Uint8Array): string
Convert an EMF buffer to a complete SVG XML string.
- buffer — EMF file data
- Returns — SVG string with
xmlns,viewBox, and all rendered elements - Throws —
Errorfor an invalid header, non-positive bounds, or certain malformed records; some malformed or truncated records instead stop parsing and return partial output
isEmf(buffer: ArrayBuffer | Uint8Array): boolean
Check the minimum 88-byte header, magic number (' EMF' at offset 40), and record type. This is a format probe, not validation of every record; conversion may still fail or return partial output.
wmf2svg(buffer: ArrayBuffer | Uint8Array): string
Convert a standard or Aldus placeable WMF buffer to SVG. The WMF path covers the common vector records used by legacy Office clipart and templates, including lines, rectangles, ellipses, polygons, text, pens, and brushes.
isWmf(buffer: ArrayBuffer | Uint8Array): boolean
Check whether a buffer has a supported standard or Aldus placeable WMF header.
Pass a Node Buffer directly: it is a Uint8Array, and its offset/length are respected. Do not pass buffer.buffer alone for a sliced Buffer, which may include unrelated bytes. Catch conversion errors for invalid/truncated input; format detection does not guarantee complete rendering.
encodeRgbaPng(width: number, height: number, rgba: Uint8Array, pixelsPerMeter?: { x: number; y: number }): Uint8Array
Encode straight-alpha RGBA8 pixels as PNG bytes without a browser canvas or host codec. Width and height must be positive safe integers, the surface must contain at most 16,777,216 pixels, and rgba must contain exactly four bytes per pixel; invalid surfaces throw an Error. When both optional pixels-per-meter values are positive integers no greater than 0xffffffff, they are written as PNG density metadata; otherwise the metadata is omitted.
Supported EMF Records
| Category | Records |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Control | HEADER, EOF, COMMENT |
| State | SAVEDC, RESTOREDC, SETWINDOWEXTEX, SETWINDOWORGEX, SETVIEWPORTEXTEX, SETVIEWPORTORGEX, SETTEXTCOLOR, SETTEXTALIGN, SETBKMODE, SETBKCOLOR, SETPOLYFILLMODE, SETMITERLIMIT, SETMAPMODE |
| Object | SELECTOBJECT, DELETEOBJECT, CREATEBRUSHINDIRECT, CREATEPEN, EXTCREATEPEN, EXTCREATEFONTINDIRECTW |
| Transform | SETWORLDTRANSFORM, MODIFYWORLDTRANSFORM |
| Drawing | MOVETOEX, LINETO, RECTANGLE, ELLIPSE, ROUNDRECT, POLYGON16, POLYLINE16, POLYBEZIER16, POLYBEZIERTO16, POLYLINETO16, POLYPOLYGON16, POLYPOLYLINE, POLYPOLYLINE16, POLYGON, POLYLINE, POLYBEZIER, POLYBEZIERTO, POLYLINETO |
| Path | BEGINPATH, ENDPATH, CLOSEFIGURE, FILLPATH, STROKEPATH, STROKEANDFILLPATH, SELECTCLIPPATH |
| Text | EXTTEXTOUTW |
| Bitmap | STRETCHDIBITS, BITBLT, ALPHABLEND, TRANSPARENTBLT |
| Arc | ARC, ARCTO, ANGLEARC, PIE, CHORD, SETARCDIRECTION |
| Gradient | GRADIENTFILL |
The table summarizes implemented record families, not full GDI compatibility. Path abort and rectangle clipping are also handled (ABORTPATH, INTERSECTCLIPRECT). Unrecognized/unimplemented records are skipped, so files with unsupported records can produce partial output.
Build Formats
| Format | File | Global |
| ------ | ------------------- | ---------------- |
| ESM | dist/index.js | — |
| CJS | dist/index.cjs | — |
| UMD | dist/index.umd.js | window.emf2svg |
Production packages do not include source maps.
Limitations
- EMF+ drawing records are not rendered. Unsupported EMF and WMF records are skipped, so output may be partial. WMF support targets common legacy Office vector and text records.
- Malformed input may throw, but some invalid or truncated records stop parsing and return partial SVG instead. Header probes and successful conversion do not validate the whole file.
- GDI raster operations are not fully implemented. Bitmap-bearing
BITBLTandSTRETCHDIBITSdo not applydwRop; source-less EMFBITBLTand WMFPATBLTsupportPATCOPYwith the current brush. - Bitmap placement and transparency are partial: source coordinates and source transforms are not applied by the supported bitmap branches, and
TRANSPARENTBLTdoes not apply its transparent color key.ALPHABLENDsupports constant opacity and supported source alpha, but is not a complete GDI blending implementation. - DIB output is generally repacked as a BMP data URI; embedded PNG/JPEG payloads pass through. Supported 32-bit source-alpha DIBs are converted to PNG to preserve alpha. That path limits surfaces to 16,777,216 pixels and accepts uncompressed data or supported RGB bitfield masks; unsupported masks or invalid surfaces throw.
- Clipping supports path intersection and replacement and rectangular intersection. Other path region combination modes fall back to replacement, and several region-based clipping records are skipped.
- Gradients support horizontal and vertical rectangle gradients. Triangle gradients are approximated with a solid average vertex color.
License
This package is licensed under the Structurify Commercial & Evaluation License (see LICENSE). Free for local development, testing, POC evaluation, and noncommercial use; commercial production use requires a commercial license.
