# Static rendering

> Render charts to SVG at build time or on the server with renderStaticSVG, for CMS pages, reports and readers without JavaScript.

Import `renderStaticSVG` from `@opendata-ai/openchart-vanilla/static` for server builds, reports and framework server components. It returns a standalone SVG string without `window`, `document`, `happy-dom`, animation, or a shared render lock. Supported specs are chart, layer, barlist, tilemap, geomap, race and table. Sankey and graph are not supported.

```ts
import { renderStaticSVG } from '@opendata-ai/openchart-vanilla/static';

const svg = renderStaticSVG(spec, {
  width: 680,
  height: 320,
  idPrefix: 'weekly-light',
  darkMode: 'off',
  precision: 3,
});
```

The light and dark SVGs behind the chart below were produced by `renderStaticSVG` when this site was built. Without JavaScript, readers see the one that matches their color scheme.

```json demo title="Global temperature anomaly" source="NASA GISS Surface Temperature Analysis (GISTEMP v4)" height=380
{
  "mark": { "type": "line", "point": true },
  "data": [
    { "year": "1900", "anomaly": -0.08 },
    { "year": "1910", "anomaly": -0.43 },
    { "year": "1920", "anomaly": -0.27 },
    { "year": "1930", "anomaly": -0.16 },
    { "year": "1940", "anomaly": 0.12 },
    { "year": "1950", "anomaly": -0.17 },
    { "year": "1960", "anomaly": -0.03 },
    { "year": "1970", "anomaly": 0.03 },
    { "year": "1980", "anomaly": 0.26 },
    { "year": "1990", "anomaly": 0.45 },
    { "year": "2000", "anomaly": 0.39 },
    { "year": "2010", "anomaly": 0.72 },
    { "year": "2020", "anomaly": 1.01 },
    { "year": "2025", "anomaly": 1.19 }
  ],
  "encoding": {
    "x": {
      "field": "year",
      "type": "temporal",
      "axis": { "format": "%Y", "tickCount": 6 }
    },
    "y": {
      "field": "anomaly",
      "type": "quantitative",
      "axis": { "title": "Anomaly (°C)", "format": "+.1f", "grid": true }
    }
  },
  "chrome": {
    "title": "Global temperature anomaly rose from +0.26°C in 1980 to +1.19°C in 2025",
    "subtitle": "Surface temperature against the 1951–1980 average, °C, selected years 1900–2025"
  }
}
```

Options include `width`, `height`, `theme`, `darkMode`, `renderer`, `watermark`, `measureText`, `idPrefix` and `precision`. `precision` is an integer from 0 through 15, or `null` for raw doubles; it defaults to 3. Text, labels, identity values and authored descriptions are not rounded. `measureText` is a per-call compiler text measurer; provide the same font metrics in each build for stable layout. `renderer` does not turn the returned SVG into a canvas.

| Option | Default | Meaning |
| --- | --- | --- |
| `width` | `640` | Compile width in pixels; authored chart/layer dimensions remain authoritative. |
| `height` | `420` | Compile height in pixels; authored chart/layer dimensions remain authoritative. For barlists, an explicit option overrides spec height; omission defaults an omitted spec height to `'auto'`. |
| `theme` | `undefined` | Per-call overrides composed with the spec/default theme. |
| `darkMode` | light | `'force'` selects dark; `'off'`, `'auto'` and omission select light on the server. |
| `renderer` | `'auto'` | Compile renderer selection; the returned artifact is always SVG. |
| `watermark` | spec/default policy | Optional brand override; explicitly authored spec and family precedence still apply. |
| `measureText` | compiler estimate | Per-call font measurement function. |
| `idPrefix` | `undefined` | Stable XML-safe scope prefix; omitted calls use deterministic standalone IDs. |
| `precision` | `3` | Integer 0–15 for geometry, or `null` to retain raw doubles. |

Static output never animates, even though live charts do by default, and contains no scripts, animation controls, focusable mark navigation, hidden HTML table or per-mark `aria-label`. Its authored mark tooltip is a `<title>`; the figure owns the accessible name.

Use a unique, stable `idPrefix` for each figure in a document. It must start with a letter or underscore and contain only letters, digits, underscores, periods or hyphens. IDs and their references share a per-call scope, so calls can interleave safely. Without `idPrefix`, ids are namespaced `ocs-<hash>-…`, where the hash covers the spec and options, so they never repeat the live charts' `oc-…` ids or those of a different unprefixed figure; identical calls still produce identical ids. The root `id` and map style scoping need an explicit prefix. Identical inputs and options produce identical bytes in the same environment. Temporal scales and date formatting can depend on the host timezone; use a consistent timezone, such as `TZ=UTC`, across builds.

Chart, layer and barlist colors and role styles are serialized as attributes, without CSS variables or a theme stylesheet. Theme them through the `theme` option. Map and tilemap output retains its scoped theme style block. The root carries `data-theme`; a prefixed root also has `id="<idPrefix>-oc-root"`. Serialization escapes XML and adds `xmlns:xlink` when an xlink attribute needs it.

## Two themes and accessible tables

Render once with `darkMode: 'off'` and once with `darkMode: 'force'`, using distinct prefixes. `auto` resolves to light on the server. The host chooses which SVG to display and supplies its own figure caption, theme-switching CSS and HTML data table. Static legends and note markers have no button roles or tab stops.

Use `a11y.description` for the figure's finding. Use `encoding.description: { field: 'rowText' }` for a data mark's authored text, or `{ value: 'Published green rate' }` for a constant description. Static shapes receive a direct `<title>` for pointer inspection, without per-mark `aria-label`; live mounts use mark descriptions for keyboard inspection. A line or area is one path per series: a description field must be constant within that series. For per-observation text, add a point layer and put the row description there.

Primary data shapes carry `data-mark`. Identity attributes such as `data-agent` or `data-day` come from non-quantitative position channels, color, detail and key fields; a series path includes only identities shared by every observation. Identity field names are normalized for attributes; reserved names receive `field-` prefixes. Errorbar caps carry no duplicate identity. Dumbbell heads and lollipop stems retain live labels and keyboard navigation, while provenance attributes belong to their primary connector or point. Isolated published observations in line and ordinary area series render as points; an ungrouped `y`/`y2` area band instead renders an isolated observation as a rule spanning its interval. Missing observations remain gaps.

For a decorative cell inside a host table, use `display: 'sparkline'` and `a11y: { hidden: true }`. Supply the value and interval text in the table itself. Layered sparkline cells share the compact display defaults and reserve space for errorbar caps and point radii.

## PNG rendering and font measurement

Import PNG rendering and font measurement from `@opendata-ai/openchart-vanilla/static-png`. The SVG-only `./static` entry loads none of the PNG/font packages. Install the optional peers in a host that needs PNG or real font measurement:

```sh
npm install @cf-wasm/resvg@^0.4.0 fontkit@^3.0.0 bidi-js@^1.1.0 unicode-properties@^2.0.2 buffer@^6.0.3
```

`renderStaticPNG` returns `Promise<Uint8Array>` in Node and Bun. Supply font bytes to use the same faces for compile-time measurement and drawing. It uses the existing static SVG renderers, then shapes text into outlines and rasterizes with WASM resvg. It needs no DOM, installed fonts, network access or native addon. The WASM bytes are inlined by its dependency, including when bundling into a single-file Bun executable. `createFontMeasure` stays synchronous; the opt-in module awaits its ESM peers during initialization. Missing measurement peers produce `StaticFontError` on use; a missing rasterizer produces `StaticPNGError`. Both name the package and its install command and preserve the loading error as `cause`. The entry can still be imported to access its error classes when peers are missing.

For a single-file Bun executable using `./static-png`, build with `bun build --compile --conditions=browser entry.ts`. The browser condition embeds Fontkit's Unicode database; without it, that dependency tries to read `data.trie` beside the executable. Normal Node and Bun execution reads the database from the installed package. SVG-only `./static` executables do not need that condition or any PNG peers.

```ts
import { readFile, writeFile } from 'node:fs/promises';
import {
  createFontMeasure,
  renderStaticPNG,
  type StaticFont,
} from '@opendata-ai/openchart-vanilla/static-png';

const fonts: StaticFont[] = [{
  family: 'Inter',
  weight: [100, 900],
  data: await readFile('InterVariable.woff2'),
}];
const png = await renderStaticPNG(spec, {
  width: 680,
  height: 320,
  scale: 2,
  darkMode: 'off',
  fonts,
});
await writeFile('chart.png', png);

const measureText = createFontMeasure(fonts);
const { width, height } = measureText('Monthly observations', 16, 700, 'Inter, sans-serif');
```

`StaticFont` accepts WOFF2, WOFF, TTF and OTF bytes as `Uint8Array`. `family` is the CSS family name to match; `weight` is a number (default 400) or an inclusive `[min, max]` range for a file with a `wght` axis. `style` is `'normal'` (default) or `'italic'`. Supply the faces used by your theme, including separate title and monospace families.

Both functions choose the first supplied family in the requested CSS stack, comparing names without case or surrounding quotes. If none match, they use the first font's family. Within that family, drawing prefers the requested style; measurement prefers normal, using italic if no normal face exists. Weight matching follows CSS's 400–500 preference rules; exact weights win over overlapping ranges, then narrower ranges win. Variable faces use the requested `wght` and automatic `opsz` at the text size, clamped to the font's axes. Other axes retain their defaults. Supply real bold and italic faces when needed; the renderer does not synthesize them.

The measurer returns shaped advance width and the font's ascent/descent/line-gap height in CSS pixels. It segments mixed scripts and applies Unicode bidirectional ordering within the SVG's default left-to-right paragraph. Newlines return the widest line and the summed line heights. A missing glyph uses the selected font's `.notdef` advance and outline, so unsupported text does not silently measure as zero. Empty text has zero width. Invalid measurement arguments, empty `fonts`, invalid descriptors and unreadable bytes throw `StaticFontError`, whose `family` identifies the failing face and whose `cause` preserves decoding details. PNG compilation binds measurements without a family override to the resolved body family; standalone `createFontMeasure` uses the first supplied font by default.

PNG options include the SVG options except `measureText`, which is derived from `fonts`. `width` and `height` are required positive finite numbers. `scale` defaults to 2, as browser PNG export does; pixel dimensions are rounded `width * scale` by `height * scale`. Tables keep their natural row geometry within that viewport; content beyond it is clipped. Invalid dimensions or scale, a rounded dimension below one or above 32,768 pixels, or more than 67,108,864 total pixels throw `StaticPNGError`. Compiler errors propagate unchanged. Dark mode uses the existing `'force'`, `'off'` and `'auto'` values; `'auto'` resolves to light without a browser.

Rasterization is sRGB. Edge antialiasing differs slightly from browser canvas export. The committed browser comparisons cover charts, tables, maps and all six theme presets in light and dark mode. Regenerate them with `bun packages/vanilla/src/__test-fixtures__/static-png/capture.mjs` after building; this uses Playwright and the browser's existing `exportPNG` function.

## Aligned figures

Use identical widths, `frame: { left: 48, right: 96 }`, temporal x domains and annotation dates on both figures. Fixed left and right values set plot margins and win over automatic label reserves; leave enough right margin for endpoint labels and outside reference labels. Neither margin may be negative, and they must leave a usable plot width. Temporal columns can specify `encoding.x.interval: 'week'`. Omission prefers an aligned calendar cadence, then falls back to the smallest positive millisecond gap; spacing that does not align with the chosen interval warns.

For a history figure, use a constant line description, an area interval band, and a point layer with row descriptions. Use the same temporal domain and frame for the weekly column figure below it. The gallery's `static/aligned-pair` demonstrates the shared plot bounds.

Run `bun scripts/static-budget.ts` to measure the consuming page's eight figures and 30 cells of each of three kinds, all in two themes. It reports combined gzip bytes, per-cell gzip bytes and rendering duration, and rejects totals above 80,000 bytes. The host's HTML and stylesheets need their own budget.
