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:
Linux / macOS:
base64 -i YourFont.woff2 -o font_base64.txtWindows (PowerShell):
[Convert]::ToBase64String([IO.File]::ReadAllBytes("YourFont.woff2")) | Out-File font_base64.txt
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:
- WOFF2:
data:font/woff2;charset=utf-8;base64, - WOFF:
data:font/woff;charset=utf-8;base64, - TTF:
data:font/ttf;charset=utf-8;base64, - OTF:
data:font/otf;charset=utf-8;base64,
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:
Using a CSS Class:
<text x="20" y="50" class="embedded-text">Sample Text</text>Using Presentation Attributes:
<text x="20" y="50" font-family="CustomEmbeddedFont" font-size="24">Sample Text</text>
Best Practices
- Subset Your Fonts: Base64 encoding increases file sizes by approximately 33%. Use font-subsetting tools to remove unused glyphs and keep the SVG lightweight.
- Prioritize WOFF2: WOFF2 offers the highest compression ratio among font formats, reducing the impact of Base64 bloat.
- Wrap CSS in CDATA (Optional): If writing pure XML,
wrap the CSS content in
<![CDATA[ ... ]]>tags to prevent XML parsers from misinterpreting special characters.