Skip to content
D
Documentation

Export images and vector PDF

how-to
9 min readUpdated

Use image export for downloads, reports and previews of a painted diagram. Exports render the scene graph, not a screenshot: the default includes the whole diagram, including content outside the camera. Use the separate static-render path for deterministic SVG on a server without a DOM.

Start from your framework's quick-start project: JavaScript, Angular, Qwik, React or Vue. Keep its entry file, stylesheet imports and framework configuration. The examples below add an export view to that project; the entry file still mounts the app.

Skip installation when your framework's quick start already installed the packages.

JavaScript:

bash
npm install @grafloria/element @grafloria/engine @grafloria/renderer

React:

bash
npm install @grafloria/react @grafloria/element @grafloria/engine @grafloria/renderer

Vue:

bash
npm install @grafloria/vue @grafloria/element @grafloria/engine @grafloria/renderer

Angular:

bash
npm install @grafloria/angular @grafloria/element @grafloria/engine @grafloria/renderer

Qwik keeps these packages in devDependencies:

bash
npm install -D @grafloria/qwik @grafloria/element @grafloria/engine @grafloria/renderer

Export

1. Share the diagram and download helper

Create src/export-data.ts in your project. Typed NodeSpec and EdgeSpec data draw two connected boxes, with Ingest on the left and Publish on the right.

ts
import type { EdgeSpec, NodeSpec } from '@grafloria/renderer';

export const nodes: NodeSpec[] = [
  {
    id: 'ingest', label: 'Ingest',
    position: { x: 60, y: 80 }, size: { width: 160, height: 70 },
    style: { fill: '#dbeafe', stroke: '#2563eb', strokeWidth: 2 },
  },
  {
    id: 'publish', label: 'Publish',
    position: { x: 340, y: 80 }, size: { width: 160, height: 70 },
    style: { fill: '#dcfce7', stroke: '#16a34a', strokeWidth: 2 },
  },
];

export const edges: EdgeSpec[] = [
  { id: 'rows', source: 'ingest', target: 'publish', label: 'rows' },
];

Create src/download.ts. SVG comes back as source text; the other four formats come back as data URLs. This browser helper wraps only SVG and starts a download.

ts
import type { ExportFormat } from '@grafloria/renderer';

export function download(format: ExportFormat, value: string): void {
  const anchor = document.createElement('a');
  anchor.href = format === 'svg'
    ? `data:image/svg+xml;charset=utf-8,${encodeURIComponent(value)}`
    : value;
  anchor.download = `diagram.${format}`;
  anchor.click();
}

export function downloadPdf(bytes: Uint8Array): void {
  const url = URL.createObjectURL(new Blob([new Uint8Array(bytes)], { type: 'application/pdf' }));
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = 'diagram.pdf';
  anchor.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
}

ExportFormat has five values:

ValueReturn from async exportResult
svgSVG source stringVector shapes and text, with styles inlined.
pngdata:image/png URLRaster image with transparency support.
jpegdata:image/jpeg URLLossy raster; the exporter supplies white behind transparent areas unless you choose a background.
webpdata:image/webp URLRaster image with configurable quality.
pdfdata:application/pdf URLVector PDF: paths remain paths and labels remain selectable text.

2. Mount the export view

Keep a live DiagramInstance and call export() from a button after the diagram appears. Angular exposes the same pipeline as exportDiagram() on DiagramCanvasComponent.

The JavaScript view uses render. The React, Vue and Qwik views use their respective GrafloriaFlow, GrafloriaFlow and GrafloriaFlow components. Each canvas has a resolved height of 400 pixels.

Use the tab for your framework. For JavaScript, change src/main.ts as shown, keeping the starter's stylesheet import. For React and Vue, add the component file and render it from your existing App component. For Angular, add the standalone component to your existing root component's imports and template as <app-export-example />. For Qwik, create src/ExportExample.tsx and re-export its default component from src/routes/index.tsx with export { default } from '../ExportExample';.

ts
// src/main.ts
import './style.css';
import { render } from '@grafloria/element';
import type { ExportFormat } from '@grafloria/renderer';
import { nodes, edges } from './export-data';
import { download } from './download';

const app = document.querySelector<HTMLDivElement>('#app');
if (!app) throw new Error('Missing #app');
app.innerHTML = '<div id="toolbar"></div><p id="status">Ready to export</p>'
  + '<div id="canvas" style="width:100%;height:400px"></div>';
const toolbar = document.querySelector<HTMLDivElement>('#toolbar');
const status = document.querySelector<HTMLParagraphElement>('#status');
if (!toolbar || !status) throw new Error('Missing export controls');
const instance = render({ nodes, edges }, '#canvas');
const formats: ExportFormat[] = ['svg', 'png', 'jpeg', 'webp', 'pdf'];
for (const format of formats) {
  const button = document.createElement('button');
  button.textContent = `Download ${format.toUpperCase()}`;
  button.onclick = async () => {
    try {
      const value = await instance.export(format, {
        padding: 32, scale: 2, backgroundColor: '#f8fafc',
        pdf: { margin: 24, metadata: { title: 'Ingest to publish' } },
        onWarnings: warnings => { status.textContent = warnings.join('; '); },
      });
      download(format, value);
      status.textContent = `Downloaded diagram.${format}. ${status.textContent}`;
    } catch (error) {
      status.textContent = String(error);
      console.error(error);
    }
  };
  toolbar.append(button);
}

The Angular two-way arrays can contain specs or live NodeModel and LinkModel values, matching the component's output types. The bindings own instance teardown when their components unmount. In a JavaScript view with a mount/unmount lifecycle, call instance.dispose() in that view's unmount handler, not after mounting it.

The Angular SVG button calls exportSvg() synchronously and downloads result.svg, displaying any result.warnings. This captures custom nodes as they stand without fetching external images; use exportDiagram('svg') when those images need embedding.

3. Download and inspect

Run your project's development command. The view shows two colored nodes, the rows edge label and five download buttons. Click Download PNG to get a raster at twice the intrinsic scale, subject to the output-size cap. Click Download SVG to inspect vector markup. Click Download PDF and select the labels in your PDF reader: they are text, not pixels. The PDF uses a 24-point page margin and a document title of “Ingest to publish”.

The React export view shows Ingest, Publish, the rows edge label and five download buttons.

The Vue view presents the same diagram and controls.

The Vue export view shows the two colored nodes, their connecting edge and the download toolbar.

Move a node and download again to export the current model. No redraw or fit call is needed for the download. Compare the task with the live Download image demo and PDF export demo.

Capture custom content and assets

Prefer async export() when the diagram contains framework-rendered custom nodes or external images. The instance captures its HTML hosts automatically, waits for the promises returned by async painters, then resolves image assets. It first tries the environment's fetch and then your assetFetcher if provided. Use onWarnings to surface partial captures and unresolved URLs beside the download control, as the export view does.

When you already have content from a separate painter, pass CustomNodeCapture data through customNodes. The following additional browser example mounts a node whose interior is supplied as a vector display list. Use this as an alternative src/main.ts in your JavaScript project, keeping its stylesheet import. The entry file calls the mount function on #app.

ts
import './style.css';
import { render } from '@grafloria/element';
import type { CustomNodeCapture, NodeSpec } from '@grafloria/renderer';
import { download, downloadPdf } from './download';

function mountCaptureExample(host: HTMLElement): () => void {
  const toolbar = document.createElement('div');
  const canvas = document.createElement('div');
  canvas.style.height = '400px';
  host.append(toolbar, canvas);
  const nodes: NodeSpec[] = [{
    id: 'chart', custom: true,
    position: { x: 60, y: 60 }, size: { width: 180, height: 100 },
  }];
  const customNodes: CustomNodeCapture[] = [{
    id: 'chart', rect: { x: 60, y: 60, width: 180, height: 100 }, fidelity: 'vector',
    content: [
      { type: 'rect', props: { x: 0, y: 0, width: 180, height: 100, fill: '#dbeafe' } },
      { type: 'rect', props: { x: 20, y: 40, width: 30, height: 40, fill: '#2563eb' } },
      { type: 'rect', props: { x: 65, y: 20, width: 30, height: 60, fill: '#16a34a' } },
    ],
  }];
  const instance = render({ nodes }, canvas, {
    renderCustomNode: (_node, element) => {
        element.innerHTML = '<svg width="180" height="100" viewBox="0 0 180 100">'
          + '<rect width="180" height="100" fill="#dbeafe" />'
          + '<rect x="20" y="40" width="30" height="40" fill="#2563eb" />'
          + '<rect x="65" y="20" width="30" height="60" fill="#16a34a" /></svg>';
    },
  });
  const status = document.createElement('span');
  const svgButton = document.createElement('button');
  svgButton.textContent = 'Download captured SVG';
  svgButton.onclick = () => {
    const result = instance.exportSvgString({
      customNodes, viewport: { x: 40, y: 40, width: 220, height: 140 },
    });
    download('svg', result.svg);
    status.textContent = result.warnings.join('; ') || 'Captured SVG downloaded';
  };
  const pdfButton = document.createElement('button');
  pdfButton.textContent = 'Download captured PDF';
  pdfButton.onclick = () => {
    const result = instance.exportPdf({ customNodes, pdf: { margin: 24 } });
    downloadPdf(result.pdf);
    status.textContent = result.warnings.join('; ') || 'Captured PDF downloaded';
  };
  toolbar.append(svgButton, pdfButton, status);
  return () => { instance.dispose(); toolbar.remove(); canvas.remove(); };
}

const host = document.querySelector<HTMLDivElement>('#app');
if (!host) throw new Error('Missing #app');
host.replaceChildren();
mountCaptureExample(host);

The mounted view and both exports show a blue and a green bar on a pale-blue rectangle. The SVG uses the explicit world-space viewport rectangle; the PDF fits the captured content. exportSvgString() returns SVG, dimensions, a view box and warnings synchronously. exportPdf() returns PDF bytes, page count and warnings synchronously. Neither waits for unfinished painters or fetches external images; use resolvedAssets when a synchronous export needs image bytes you already hold.

For automatic framework custom-node rendering, use the binding patterns in Customize rendering contracts, rather than maintaining a parallel capture list.

Render deterministic SVG on a server

Use renderStatic from the element package, or renderToStaticSVG from the renderer package. Both return the same static result. No mounted browser instance is involved in this path.

In a Node project, install the packages and a TypeScript runner:

bash
npm install @grafloria/element @grafloria/engine @grafloria/renderer
npm install --save-dev tsx @types/node

Copy export-data.ts from the first step alongside export-static.ts. This script creates a standalone file, inserts the returned stylesheet into it, and checks two independent renders for identical output. The file's Node type reference makes node:fs available even when the starter's TypeScript configuration limits ambient types; keep the browser configuration unchanged.

ts
/// <reference types="node" />
import { writeFileSync } from 'node:fs';
import { renderStatic } from '@grafloria/element';
import { renderToStaticSVG } from '@grafloria/renderer';
import type { StaticRenderOptions, StaticRenderResult } from '@grafloria/renderer';
import { nodes, edges } from './export-data';

const options: StaticRenderOptions = {
  nodes, edges, width: 520, height: 300, standalone: true,
};
function artifact(result: StaticRenderResult): string {
  return result.svg.replace(/^(<svg[^>]*>)/, `$1<style>${result.css}</style>`);
}
const first = artifact(renderStatic(options));
const second = artifact(renderToStaticSVG(options));
if (first !== second) throw new Error('Static renders differ');
writeFileSync('diagram.svg', first, 'utf8');
console.log('Wrote diagram.svg; independent renders match.');
bash
npx tsx export-static.ts

Open diagram.svg: it contains the same Ingest and Publish boxes and connecting edge. StaticRenderResult separates svg, css, the full layer html and the hydration snapshot. Include css when publishing static markup; standalone: true adds the SVG namespace, not theme inlining. Keep the snapshot with the same specs for interactive hydration; see Instance and lifecycle.

Static rendering includes SVG nodes, ports, edges, labels and group frames. It does not render framework HTML-layer custom components; those mount on hydration. The live Server-side export demo demonstrates the same spec-to-SVG path and byte comparison.

Export a renderer-owned scene tree

Use the instance methods for application downloads. The lower-level exportSvg and exportPdf functions are for code that already owns a rendered VNode tree. They do not capture DOM hosts or fetch assets.

This browser entry file uses SVGRenderer to render the model of a real mounted diagram. It then passes that exact tree to both serializers. Use it as another alternative src/main.ts; it mounts into #app and keeps the starter's stylesheet import. This goes below the instance only to show the tree-to-file boundary; keep the instance pipeline for custom HTML content.

ts
import './style.css';
import { render } from '@grafloria/element';
import { SVGRenderer, exportSvg, exportPdf } from '@grafloria/renderer';
import { nodes, edges } from './export-data';
import { download, downloadPdf } from './download';

function mountTreeExport(host: HTMLElement): () => void {
  const canvas = document.createElement('div');
  canvas.style.height = '400px';
  const button = document.createElement('button');
  button.textContent = 'Download scene SVG and PDF';
  const note = document.createElement('p');
  host.append(button, note, canvas);
  const instance = render({ nodes, edges }, canvas);
  button.onclick = () => {
    const renderer = new SVGRenderer(instance.getEngine());
    try {
      const tree = renderer.render({ x: 0, y: 0, width: 520, height: 300 }, 1);
      const svg = exportSvg(tree, { padding: 32 });
      const pdf = exportPdf(tree, { margin: 24, metadata: { title: 'Scene export' } });
      download('svg', svg.svg);
      downloadPdf(pdf.pdf);
      note.textContent = [...svg.warnings, ...pdf.warnings].join('; ') || 'Scene files downloaded';
    } finally {
      renderer.dispose();
    }
  };
  return () => { instance.dispose(); canvas.remove(); button.remove(); note.remove(); };
}

const host = document.querySelector<HTMLDivElement>('#app');
if (!host) throw new Error('Missing #app');
host.replaceChildren();
mountTreeExport(host);

For a non-default theme, pass the same theme to the renderer and serializers so CSS-mode paint resolves consistently. Disposing this temporary serializer renderer does not dispose the mounted diagram's instance.

Options that matter

Image and capture options

Pass ExportOptions to the instance's async or synchronous export methods.

OptionTypeDefaultWhat it does
paddingnumber20Adds world-space margin around content; ignored with an explicit viewport.
viewportRectangleContent boundsChooses an exact world-space rectangle.
scopeExportScopecontentChooses whole content, a viewport slice or live selection.
scalenumber1Multiplies intrinsic image dimensions, not the world-space view box.
backgroundColorstringTransparentPaints behind the content; JPEG supplies white if omitted.
qualitynumber0.92Sets JPEG/WebP quality from 0 to 1.
maxSizenumber4000 on the raster pathReduces scale to keep each side within the cap, without cropping. SVG accepts an explicit cap.
minSizenumber1Sets the minimum intrinsic dimension per side.
xmlDeclarationbooleanfalseAdds an XML prolog to SVG.
foreignObjectForeignObjectModeserializeControls HTML-in-SVG serialization.
customNodesReadonly capture arrayCaptured by the instanceOverrides HTML-host captures; [] excludes widgets.
htmlFallbackHtmlFallbackModeforeignObjectChooses how HTML-only custom captures appear.
customNodeTimeoutnumber5000 msBounds async-painter waiting; 0 captures immediately and reports unfinished painters.
assetFetcherAssetFetcherNoneSupplies a second fetch tier after the environment's fetch fails.
resolvedAssetsReadonlyMap<string, string>NoneMaps external URLs to pre-resolved data URIs; matched URLs are not fetched again.
assetTimeoutnumber5000 ms per image per tierBounds external-image fetching.
assetMaxBytesnumber5 MBRefuses oversized fetched images with a warning.
embedFontCssstringNoneInserts font CSS into SVG definitions; use embedded data-URI sources.
embedFontsFontSource arrayNoneBuilds embedded @font-face rules from supplied font bytes.
rasterBackendRasterBackendBrowser canvas backendSupplies the SVG-to-pixels engine for raster formats.
pdfPdfExportOptionsOne page, 36-point marginsSets PDF paper, margins and metadata.

The scope values are content (all drawn content), viewport (a world-space slice) and selection (only currently selected nodes and links). Supply an explicit viewport rectangle whenever you want a fixed slice, as the capture example does. SVG and raster exports reject scope: 'viewport' without a rectangle; PDF uses content bounds when the rectangle is omitted.

foreignObject accepts serialize (keep HTML), placeholder (replace it with a marked box) and omit (leave it out). htmlFallback accepts foreignObject (carry HTML in SVG), placeholder and omit. A custom capture's fidelity is vector (SVG primitives usable in PDF), html (HTML-only, reported as a fidelity risk) or empty (a marked box and warning).

Static-render options

StaticRenderOptions describes the server canvas and camera, rather than an export crop.

OptionTypeDefaultWhat it does
nodes, edgesSpec arraysEmptySupply the scene data.
groupsGroupSpec arrayNoneAdds group and lane frames after their children.
themeThemeBuilt-in light themeSupplies the returned stylesheet.
width, heightnumber800, 600 CSS pxSet canvas dimensions and standalone SVG dimensions.
zoomnumber1Sets camera scale.
viewport{ x: number; y: number }{ x: 0, y: 0 }Sets camera origin in world coordinates.
instanceIdstringgrafloria-ssrSets CSS scope; use a distinct id for each diagram on one page.
fitViewbooleanfalseFrames content instead of using the supplied camera.
fitPaddingnumber40 CSS pxSets padding for static fit-to-content.
standalonebooleanfalseAdds xmlns for a standalone SVG file.

Pitfalls and environment boundaries

  • Export after the canvas has painted. Use a user-facing button after mounting, rather than an immediate export during initialization.
  • Async export waits for painter promises, not arbitrary later UI updates. A timeout exports the content available so far and reports a warning. Synchronous exports cannot wait or fetch.
  • HTML carried in foreignObject works in browser SVG, but PDF cannot represent it. Prefer vector captures for cross-format fidelity. PDF also omits Gaussian-blurred shadows; inspect warnings rather than assuming every SVG effect survives.
  • Font embedding applies to the SVG pipeline; the vector PDF writer uses its base-font text pipeline. Do not expect embedFonts to embed fonts in PDF.
  • A server-side image proxy needs an allowlist and protection against requests into private networks. Do not turn assetFetcher into an unrestricted URL proxy.
  • Node needs a raster engine for PNG/JPEG/WebP. Use the shipped createResvgBackend for PNG or createSharpBackend for all three raster formats, supplying the corresponding installed module. SVG static rendering needs neither.

isBrowser tests for both window and document; now supplies a clock even without performance. Neither is needed for deterministic static rendering. printDocument opens the browser print dialog through a hidden iframe for an already-built print document; it is browser-only, not a Node PDF renderer.

These image downloads do not include an editable document. For the authors' embedModel flow—SVG or PNG carrying the full integrity-checked document, loaded through importDiagram—use Save and restore documents. That page covers reopening and protecting newer edits; JPEG and WebP do not carry the embedded document.

Was this page helpful?