How to Embed Fonts in SVG Using Base64 Data URIs

Embedding font files directly into an SVG using Base64 data URIs creates self-contained, portable graphic files that render text consistently across any platform or browser without relying on external assets or local font installations. This guide explains the process of converting font binaries into Base64 strings, structuring the @font-face CSS inside an SVG’s <defs> tag, and applying the embedded typography to text elements.

1. Convert the Font File to Base64

To embed a font, you must first convert the binary file (preferably .woff or .woff2 for smaller file sizes) into a Base64-encoded string.

You can perform this conversion via terminal commands:

Alternatively, you can use online Base64 encoders or build tools like Webpack or Vite.

2. Identify the Correct MIME Type

Match the Data URI MIME type to your source font format:

3. Add the @font-face Rule to the SVG

Place a <style> block inside the <defs> section of your SVG. Define the @font-face rule using the Base64 Data URI inside the src attribute.

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 600 150" width="100%" height="100%">
  <defs>
    <style type="text/css">
      @font-face {
        font-family: 'CustomEmbeddedFont';
        src: url('data:font/woff2;charset=utf-8;base64,d09GRgABAAAAAA...') format('woff2');
        font-weight: normal;
        font-style: normal;
      }

      .embedded-text {
        font-family: 'CustomEmbeddedFont', sans-serif;
        font-size: 32px;
        fill: #222222;
      }
    </style>
  </defs>

  <text x="20" y="80" class="embedded-text">
    This text uses the Base64 embedded font.
  </text>
</svg>

4. Apply the Font to SVG Text Elements

Once declared, reference the font-family name defined in your @font-face rule using standard CSS classes, inline styles, or presentation attributes:

Best Practices