ScreenshotNeo

BlogHow-to

How to Include Fonts in SVG Exports with html-to-image

Embed web fonts in html-to-image SVG exports with getFontEmbedCSS, custom font CSS, format selection, debugging steps, and reusable code.

By the ScreenshotNeo team30 September 20267 min read

How to Include Fonts in SVG Exports with html-to-image

Use html-to-image’s font embedding pipeline. Call getFontEmbedCSS(element) once, then pass the returned CSS to toSvg through the fontEmbedCSS option:

const fontEmbedCSS = await htmlToImage.getFontEmbedCSS(element);
const svgDataUrl = await htmlToImage.toSvg(element, { fontEmbedCSS });

The library finds @font-face rules, downloads the referenced font files, converts them to data URLs, and adds the processed rules to the cloned node used for the SVG export. See the font embedding section of the html-to-image README and the TypeScript option definitions.

1. Working example

This browser example loads a Google-style web font, embeds it, and downloads an SVG. Replace the font URL with a file you control in production.

html-to-image discovers the font rule, fetches the file, and embeds it into the SVG export.
html-to-image discovers the font rule, fetches the file, and embeds it into the SVG export.
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    @font-face {
      font-family: "Demo Sans";
      src: url("https://example.com/fonts/demo-sans.woff2") format("woff2");
      font-weight: 400;
      font-style: normal;
      font-display: swap;
    }
    #card {
      width: 520px;
      padding: 32px;
      color: #172033;
      background: white;
      font-family: "Demo Sans", sans-serif;
    }
  </style>
</head>
<body>
  <article id="card">
    <h1>Font-safe SVG</h1>
    <p>This text should keep its web font after export.</p>
  </article>
  <button id="save">Save SVG</button>
  <script type="module">
    import * as htmlToImage from "https://cdn.jsdelivr.net/npm/html-to-image/+esm";

    const element = document.querySelector("#card");
    document.querySelector("#save").addEventListener("click", async () => {
      const fontEmbedCSS = await htmlToImage.getFontEmbedCSS(element);
      const svgDataUrl = await htmlToImage.toSvg(element, { fontEmbedCSS });
      const link = document.createElement("a");
      link.download = "font-safe-card.svg";
      link.href = svgDataUrl;
      link.click();
    });
  </script>
</body>
</html>

The URL in @font-face must be reachable from the page during export. In a real app, serve the font with CORS headers that permit the page origin, or host the font on the same origin.

2. Reuse embedded CSS for repeated exports

Font parsing and downloading can be repeated unnecessarily when exporting several elements that use the same font set. Compute the CSS once and reuse it:

const fontEmbedCSS = await htmlToImage.getFontEmbedCSS(document.body);

const svgUrls = await Promise.all(
  document.querySelectorAll(".export-card").values().map((card) =>
    htmlToImage.toSvg(card, { fontEmbedCSS })
  )
);

Use an element that contains the relevant @font-face declarations, or pass a custom CSS string with the declarations yourself. Reuse is especially useful for batch exports, but regenerate the CSS if the font files or declarations change.

3. Supply custom fontEmbedCSS

A custom string is useful when your global stylesheet is inaccessible to the cloned document or when you want to control exactly which faces are embedded:

const fontEmbedCSS = `
@font-face {
  font-family: "Brand Sans";
  src: url("https://static.example.com/brand-sans.woff2") format("woff2");
  font-weight: 400;
  font-style: normal;
}
`;

const svgDataUrl = await htmlToImage.toSvg(element, {
  fontEmbedCSS
});

The family name, weight, and style in this CSS must match the computed styles on the element. A declaration for Brand Sans does not help text rendered with BrandSans or with a different weight that has no matching face.

4. Choose a font format

If one @font-face rule lists multiple formats, html-to-image can retain a preferred format with preferredFontFormat. If you leave it unset, the documented behavior is to download and embed all listed formats.

const svgDataUrl = await htmlToImage.toSvg(element, {
  preferredFontFormat: "woff2"
});

Use the format that is actually available and readable in your target viewer. Selecting a format that is absent can leave the export without a usable source.

5. Do not disable font embedding accidentally

skipFonts: true tells html-to-image to skip font downloading and embedding. Leave it unset (or set it to false) when preserving web fonts is the goal:

const svgDataUrl = await htmlToImage.toSvg(element, {
  skipFonts: false
});

Skipping fonts can make exports faster and smaller when the target environment already has the exact fonts installed, but it makes the SVG dependent on that environment.

6. Localhost fonts and fallback rendering

A page rendering correctly is not proof that the exported SVG contains the same font. The browser may have loaded the font for normal layout while the export step cannot fetch it for the cloned document.

  • Open the font URL directly from the page origin and verify it returns the font bytes, not an HTML error page.
  • Check the browser console and network panel for CORS, 404, or opaque-response errors.
  • Confirm the @font-face rule is visible to the export code and that its family name exactly matches the element’s computed font-family.
  • For localhost development, use a stable HTTP origin rather than mixing file://, different ports, and HTTPS.
  • Try a production-like host and the exact browser/package versions used by your users.

A project report described fallback output with locally served fonts and custom fontEmbedCSS. Treat that report as a diagnostic example, not as a universal cause; the key dependency remains that the referenced font URL can be discovered and fetched during export.

7. Verify the SVG itself

Inspect the returned data URL instead of judging only the on-screen preview:

const svgDataUrl = await htmlToImage.toSvg(element);
const svgText = decodeURIComponent(svgDataUrl.split(",")[1]);
console.log(svgText.includes("@font-face"));
console.log(svgText.slice(0, 500));

Depending on encoding, the data URL may use base64 rather than URI encoding. Decode it accordingly, then search for an embedded data:font/... source and the expected family name. Open the saved SVG in the target viewer because different viewers support embedded font formats differently.

8. Troubleshooting checklist

Symptom Likely cause Fix
Fallback font in SVG No reachable @font-face source, mismatched family, or skipped fonts Verify the URL and family/weight/style; remove skipFonts: true; inspect the SVG.
Font works in page but not export Export clone cannot fetch the stylesheet or font due to CORS or origin differences Serve CSS and font with appropriate CORS headers, use same-origin assets, or provide explicit fontEmbedCSS.
Only one weight is wrong The requested weight has no matching embedded face Add an @font-face rule for that weight and ensure the element uses the declared value.
Export hangs or fails while downloading fonts Font URL timeout, redirect, or server error Test the URL independently, remove broken sources, and retry with a reachable format.
Large SVG files Several font formats or multiple large font files embedded Use preferredFontFormat, subset fonts upstream, and reuse one computed CSS string.
Firefox-only failure A reported issue affected font processing in versions 1.11.12 and later Reproduce with the exact installed package and browser versions, check the project issue status, and test a current release before changing application code.

9. Performance and reliability

  • Cache the CSS: call getFontEmbedCSS once for a batch that shares fonts.
  • Limit formats: embedding one appropriate format avoids downloading duplicate files.
  • Keep font files small: subset character ranges and remove unused weights where your font pipeline allows it.
  • Wait for the right state: trigger export after the page has applied the intended font, not immediately after inserting the element.
  • Use deterministic assets: version font URLs so a changed file cannot silently produce a different export.
  • Test the consumer: browser previews, design tools, PDF converters, and image pipelines may have different SVG font support.

10. Complete export helper

import * as htmlToImage from "html-to-image";

export async function elementToSvg(element) {
  if (!(element instanceof HTMLElement)) {
    throw new TypeError("elementToSvg expects an HTMLElement");
  }

  await document.fonts.ready;
  const fontEmbedCSS = await htmlToImage.getFontEmbedCSS(element);

  return htmlToImage.toSvg(element, {
    fontEmbedCSS,
    preferredFontFormat: "woff2",
    cacheBust: true
  });
}

const svg = await elementToSvg(document.querySelector("#card"));
const blob = await (await fetch(svg)).blob();
const href = URL.createObjectURL(blob);
const link = Object.assign(document.createElement("a"), {
  href,
  download: "card.svg"
});
link.click();
URL.revokeObjectURL(href);

11. Or skip the browser setup

If you need a screenshot or PDF rather than an SVG with editable vector text, ScreenshotNeo provides a single request endpoint. It handles the browser session and returns PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation.

ScreenshotNeo removes common consent banners, popups, and chat widgets before capture.
ScreenshotNeo removes common consent banners, popups, and chat widgets before capture.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers identify the page verdict and billing status. An MCP server lets Claude, Cursor, and other MCP clients call take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.

12. FAQ

Does html-to-image convert text to paths?

No. Text remains text in the SVG, while the font is supplied through embedded CSS and font data. Viewer support still matters.

Should I always use getFontEmbedCSS?

Use it when you want explicit, reusable font CSS or repeated exports. For a one-off export, the library can perform the embedding during toSvg without you storing the result.

Why does a system-installed font work without embedding?

The viewer may already have that font, but the SVG is then less portable. Embedding makes the file independent of the viewer’s installed fonts when the viewer supports the embedded format.

Can I embed only one font weight?

Yes. Provide only the required @font-face rule in your stylesheet or custom fontEmbedCSS, and use the matching weight on the element.