---
title: "Subset a font for web page text in C#"
url: https://recursiveai.org/onefont/cookbook/subset-font-to-characters-used-on-a-web-page/
description: "Keep only the character mappings you need for known page text. The C# example subsets a TrueType font and shows what happens to OpenType shaping."
version: "1.6.0"
---

# Subset a font for web page text in C#

**onefont** is a free, open-source font and text-shaping library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneFont) · [GitHub](https://github.com/recursive-ai-oss/onefont-csharp) · [Docs](https://recursiveai.org/onefont/docs/) · [Download example (.zip)](https://recursiveai.org/onefont/cookbook/subset-font-to-characters-used-on-a-web-page/subset-font-to-characters-used-on-a-web-page.zip)

Keep only the characters in `Café` from the included `NotoSans-Regular.ttf`. The subset drops the original shaping rules.

```shell
dotnet add package RecursiveAI.OneFont
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using System.Text;
using OneFont;

const string pageText = "Café";
var face = FontFace.Load(File.ReadAllBytes(
    "NotoSans-Regular.ttf"));
var subset = new FontSubsetter(face);
foreach (var rune in pageText.EnumerateRunes())
{
    int glyph = face.GetGlyphIndex(rune.Value);
    if (glyph == 0)
        throw new ArgumentException(
            $"Missing: {rune}");
    subset.Map(rune.Value, glyph);
}
byte[] ttf = subset.Build();
File.WriteAllBytes("page.ttf", ttf);
Console.WriteLine(
    $"Wrote page.ttf for {pageText}");
```

Paste the code above into Program.cs of a new `dotnet new console` project and `dotnet run`, or unzip [the example](https://recursiveai.org/onefont/cookbook/subset-font-to-characters-used-on-a-web-page/subset-font-to-characters-used-on-a-web-page.zip) and `dotnet run`.

If you paste the snippet into a new project, copy a `.ttf` next to `Program.cs` as `NotoSans-Regular.ttf` or change the path in `File.ReadAllBytes`.

```text
Wrote page.ttf for Café
```

[Convert `page.ttf` to WOFF2](https://recursiveai.org/onefont/cookbook/convert-ttf-otf-to-woff2/) to serve it as a web font.

The ZIP includes Noto Sans under the SIL Open Font License. If the input font has no glyph for a scalar in `pageText`, the example throws `ArgumentException` instead of mapping that scalar to the missing-glyph box. `Build()` accepts TrueType and OpenType-CFF outlines, not CFF2.

## Variations

**Read a simple HTML file.** Save this as `page.html` next to `Program.cs`:

```html
<p>Caf&eacute; du <em>jour</em></p>
```

Replace the `const string pageText` line with the following and leave the same `EnumerateRunes()` loop in place. Strip the tags first, then decode entities such as `&eacute;`.

```csharp
string html = File.ReadAllText("page.html");
string text = System.Text.RegularExpressions.Regex
    .Replace(html, "<[^>]+>", "");
string pageText = System.Net.WebUtility
    .HtmlDecode(text).Trim();
```

```text
Wrote page.ttf for Café du jour
```

This handles the simple markup shown, not arbitrary HTML: it doesn’t exclude scripts or hidden content or add spaces between block elements. For a full page, collect the rendered text for the font instead.

**Check the resulting character map.** Add this after the snippet at the top. `Z` exists in the source font, but isn’t mapped in the subset.

```csharp
var page = FontFace.Load(ttf);
Console.WriteLine($"C: {page.HasGlyph('C')}");
Console.WriteLine($"é: {page.HasGlyph('é')}");
Console.WriteLine($"Z: {page.HasGlyph('Z')}");
```

```text
C: True
é: True
Z: False
```

## Related recipes

- [Check if a font supports a character](https://recursiveai.org/onefont/cookbook/font-supports-character/)
- [Convert TTF or OTF to WOFF2 or WOFF](https://recursiveai.org/onefont/cookbook/convert-ttf-otf-to-woff2/)

---

## The short answer

Put the text that will use the font into one string. Walk its Unicode scalars with `EnumerateRunes()`, look up the source glyph for each one, and pass the scalar and glyph ID to `FontSubsetter.Map`. `Build()` writes a font with those character mappings. The example maps `C`, `a`, `f`, and `é`. TrueType composite glyphs bring along their component glyphs, so the glyph data need not contain exactly four entries.

## Can a website serve only the glyphs it uses instead of the whole font?

Yes, when you know the text in advance, such as a fixed heading or an exported page. Collect the rendered text for that face, including punctuation, spaces, and all translations you intend to serve with the subset. Pass text, not HTML markup. For example, if the HTML contains `Caf&eacute;`, map the decoded `Café`, not the characters in the entity name. If multiple weights or styles have their own font files, build each subset from the text that uses that face.

`EnumerateRunes()` operates on Unicode scalar values, not individual UTF-16 code units. A character outside the Basic Multilingual Plane gets one lookup rather than two surrogate lookups. It isn’t a grapheme splitter: a decomposed `e` plus a combining acute accent gives two scalar values, whereas the precomposed `é` in the sample gives one. Use the same representation for the string you subset and the page text you serve.

If the page will show what users type, arbitrary translations, or other text unknown at export time, a subset based on the initial page won’t cover it. Serve the full font for those sections or deliberately arrange a fallback and test that it covers the additional text. Check that the source license permits modifying and serving the font. The [subsetting docs](https://recursiveai.org/onefont/docs/building/) note that the font’s embedding flags are copied, not enforced.

## Does subsetting a web font preserve kerning and ligatures?

Not with this scalar-mapping recipe. As the [subsetting docs](https://recursiveai.org/onefont/docs/building/) explain, the output keeps glyph outlines and advances but drops the original `GSUB`, `GPOS`, `GDEF`, and `kern` tables. Having every character available is not the same as preserving how the original font joins letters, chooses alternate shapes, or positions marks. A retained glyph can have the same advance even when the spacing of a whole word changes because its kerning pairs are gone.

You can supply a known sequence and its glyph explicitly with `MapSequence`, which writes a new substitution rule; it doesn’t recover the original rules. For text that relies on the source font’s full shaping behavior, don’t use this character-only subset as a drop-in replacement. Variable fonts are subset at their default instance, with variation tables dropped.
