Working with Fonts and Text in SVG – C#

Text rendering is one of the most sensitive parts of SVG processing. The same SVG document can produce different visual results depending on font availability, operating system, or rendering environment. This often leads to situations where SVG text looks correct in a browser but renders differently when converted on a server.

Aspose.SVG for .NET provides a complete API for working with SVG text, including creating text elements, applying custom fonts, handling font fallback, and embedding fonts directly into SVG documents. This makes it possible to generate predictable and platform-independent output when converting SVG to images or PDF.

In this article, you will learn how to:

All examples use Aspose.SVG for .NET and focus on real-world server-side scenarios, such as SVG to image or SVG to PDF conversion, where system fonts cannot be reliably assumed.

Understanding How Fonts Work in SVG

Unlike HTML, SVG handles text and fonts in a more explicit and declarative way. Fonts in SVG are not automatically resolved based on the browser or operating system alone — instead, they follow a well-defined lookup and fallback process defined by the SVG and CSS specifications.

Understanding this process is essential before working with custom fonts, @font-face, or SVG-to-PDF conversion.

Font Resolution in SVG

When an SVG document contains text, the rendering engine resolves fonts in the following order:

  1. Explicit font declarations – Fonts defined directly on elements using:

    • font-family attributes
    • inline style attributes
    • CSS rules inside <style>
  2. Embedded fonts – Fonts defined via @font-face inside the SVG document.

  3. External or custom font sources – Fonts provided by the rendering engine, such as:

    • custom font folders configured via API
    • system-installed fonts
  4. Generic fallback fonts – If no matching font is found, a generic family such as sans-serif or serif is used.

Refer to the article SVG Styles: CSS vs Inline vs Attributes to learn more about CSS rules, inline styles, and presentation attributes.

SVG Is Not HTML

SVG uses CSS syntax, but its font handling differs from HTML:

These differences explain why SVG text often behaves unexpectedly when system fonts or implicit inheritance are used. As a result, SVG documents often require explicit font configuration to ensure consistent appearance.

To learn how to diagnose and fix SVG styling and font issues, see the article Common SVG Styling and Font Issues.

Why Fonts Behave Differently During Conversion

When converting SVG to formats such as PNG or PDF:

This is why an SVG that looks correct in one environment may render differently when converted on a server or CI system.

Key Takeaway

To work with fonts reliably in SVG:

  • Always specify explicit font-family values.
  • Include fallback fonts.
  • Embed fonts using @font-face or provide them via configuration.
  • Don’t rely on the required font being installed on the machine where the SVG will be rendered or converted.

The following sections demonstrate these principles in practice using Aspose.SVG for .NET.

Using Custom Fonts via Configuration

The most straightforward way to work with text in SVG is to create and configure <text> elements directly through the SVG DOM. This approach gives you full control over positioning and basic font properties without relying on CSS or external styles.

Below is a simple example that demonstrates how to create a text element and render SVG text using a custom font by configuring a fonts lookup directory.

1using Aspose.Svg.Saving;
2using Aspose.Svg.Rendering.Image;
3using Aspose.Svg.Converters;
4using System.IO;
 1// Render SVG text with a custom font using FontsSettings in Aspose.SVG for .NET
 2
 3// Create an instance of the Configuration class 
 4using (Configuration configuration = new Configuration())
 5{
 6    // Configure custom fonts folder
 7    IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
 8
 9    userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
10
11    // Create SVG document WITH configuration
12    using (SVGDocument document = new SVGDocument(configuration))
13    {
14        // Create <text> element
15        SVGTextElement text = (SVGTextElement)document.CreateElementNS("http://www.w3.org/2000/svg", "text");
16
17        text.SetAttribute("x", "50");
18        text.SetAttribute("y", "100");
19        text.SetAttribute("font-family", "Montserrat");
20        text.SetAttribute("font-size", "24");
21        text.TextContent = "Custom Font Example";
22
23        document.RootElement.AppendChild(text);
24
25        // Convert SVG to JPG
26        ImageSaveOptions saveOptions = new ImageSaveOptions(ImageFormat.Jpeg);
27
28        Converter.ConvertSVG(document, saveOptions, Path.Combine(OutputDir, "custom-font.jpg"));
29    }
30}

The Configuration class serves as the central container for all rendering settings. In this example, a Configuration creates an isolated processing environment into which a document is passed to ensure custom settings are applied. The IUserAgentService is used to configure the font search path using FontsSettings.SetFontsLookupFolder(), allowing the rendering engine to find and apply the specified font when converting text to an image.

Using @font-face in SVG

In many SVG scenarios, relying on system-installed fonts is not reliable. The same SVG may look different if the target system lacks a specific font. To ensure consistent rendering, you can embed custom fonts directly into your SVG using the @font-face rule.

This approach allows you to:

Below is a practical example that demonstrates how to embed a font in an SVG and render it in a PDF using Aspose.SVG for .NET.

1using Aspose.Svg.Saving;
2using Aspose.Svg.Converters;
3using System.IO;
 1// Embed custom fonts into SVG using @font-face programmatically and convert to PDF with Aspose.SVG for .NET
 2
 3// Create SVG document
 4using (SVGDocument document = new SVGDocument())
 5{
 6    SVGSVGElement root = document.RootElement;
 7
 8    // Create <style> element
 9    SVGStyleElement style = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
10
11    style.SetAttribute("type", "text/css");
12
13    // Define @font-face rule programmatically
14    style.TextContent =
15        "@font-face { " +
16        "  font-family: 'VeinlineRegular'; " +
17        "  src: url(https://assets.ithillel.ua/wiki/VeinlineRegular.ttf); " +
18        "} " +
19        "text { " +
20        "  font-family: 'VeinlineRegular', sans-serif; " +
21        "  font-size: 28px; " +
22        "  fill: #2c3e50; " +
23        "}";
24
25    // Append <style> to SVG root
26    root.AppendChild(style);
27
28    // Create <text> element
29    SVGTextElement text = (SVGTextElement)document.CreateElementNS("http://www.w3.org/2000/svg", "text");
30    text.SetAttribute("x", "40");
31    text.SetAttribute("y", "90");
32    text.TextContent = "SVG text rendered with @font-face";
33
34    root.AppendChild(text);
35
36    // Convert SVG to PDF
37    PdfSaveOptions pdfOptions = new PdfSaveOptions();
38    Converter.ConvertSVG(document, pdfOptions, Path.Combine(OutputDir, "svg-font-face.pdf"));
39}

Key Points

  • @font-face allows embedding remote or local fonts: In the example, the font is loaded from a URL, but it can also be loaded from a local folder.
  • Fallback fonts are specified: 'VeinlineRegular', sans-serif ensures a fallback if the embedded font fails.
  • Consistent output across platforms: The same PDF or image will look identical regardless of system fonts.
  • Base URI matters: When using a remote font URL, set a base URI in the SVGDocument constructor to resolve relative paths.

This example is particularly useful for scenarios where:

  • You generate reports, invoices, or certificates in SVG and convert them to PDF.
  • Your SVG must render identically on any server, regardless of installed fonts.
  • You need to embed corporate or licensed fonts directly into the SVG.

Font Lookup and Fallback Behavior

When rendering SVG text, Aspose.SVG for .NET uses a font search mechanism to locate the specified font. If the requested font is not available on the system or in the custom font folders, a fallback font is automatically applied. Understanding this behavior is crucial to avoid unexpected rendering results, such as Arial being displayed instead of the desired font.

Why SVG Fonts Fall Back to Arial or Default Fonts

SVG supports font family lists, just like CSS:

1font-family: 'Montserrat', 'Arial', sans-serif;

The renderer evaluates each font from left to right and selects the first available font. This makes fallback lists a critical part of predictable SVG rendering. If no fallback is specified, the renderer applies a default font, which may vary depending on the platform or rendering engine.

The following example demonstrates how custom fonts are prioritized and what happens when a font is missing.

1using Aspose.Svg.Saving;
2using Aspose.Svg.Converters;
3using System.IO;
 1// Render SVG text to PDF with font fallback when custom fonts are unavailable using Aspose.SVG for .NET
 2
 3// Create configuration and specify custom fonts directory
 4using (Configuration configuration = new Configuration())
 5{
 6    IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
 7    userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
 8
 9    // Load existing SVG document
10    using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"), configuration))
11    {
12        // Find the first <text> element in the document
13        SVGTextElement text = document.QuerySelector("text") as SVGTextElement;
14
15        if (text != null)
16        {
17            // Set custom font with fallback
18            text.SetAttribute("font-family", "'Montserrat', sans-serif");                        
19        }
20        document.Save(Path.Combine(OutputDir, "font-fallback.svg"));
21
22        // Convert SVG to PNG
23        ImageSaveOptions saveOptions = new ImageSaveOptions();
24        Converter.ConvertSVG(document, saveOptions, Path.Combine(OutputDir, "font-fallback.png"));
25    }
26}

Production Tips

  • Custom fonts folder: SetFontsLookupFolder allows you to prioritize your own fonts before system fonts.
  • Automatic fallback: If the requested font does not exist, Aspose.SVG will automatically use a fallback font (often Arial or the default sans-serif).
  • Consistent results: To ensure predictable rendering, always provide your custom fonts or use @font-face embedding.
  • Font lookup order: Custom fonts → system-installed fonts → generic fallback.

This example helps developers understand why sometimes SVG text may not render in the expected font and how to control fallback behavior by properly configuring font lookup.

Note: When saving an SVG document, Aspose.SVG preserves font-family declarations but does not automatically embed or resolve font files. Font lookup folders are used only during rendering or conversion. To make a custom font work within the SVG, it must be defined with @font-face.

Ensuring Consistent Text Rendering During SVG Conversion

Rendering SVG text consistently across different platforms can be challenging. Differences in system-installed fonts, missing fonts, or conflicting inline styles can lead to unexpected results when converting SVG to images or PDF.

Aspose.SVG for .NET allows you to control font lookup, embed fonts, and normalize text styles, ensuring that your output is consistent regardless of the environment.

1using Aspose.Svg.Rendering;
2using Aspose.Svg.Rendering.Image;
3using Aspose.Svg.Rendering.Pdf;
4using System.IO;
 1// Ensure consistent SVG text rendering across PNG and PDF outputs using custom fonts
 2
 3// Create configuration to specify custom fonts folder
 4using (Configuration configuration = new Configuration())
 5{
 6    IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
 7
 8    // Set folder containing your custom fonts
 9    userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
10
11    // Create SVG document with configuration
12    using (SVGDocument document = new SVGDocument(configuration))
13    {
14        // Create <text> element
15        SVGTextElement text = (SVGTextElement)document.CreateElementNS("http://www.w3.org/2000/svg", "text");
16
17        text.SetAttribute("x", "50");
18        text.SetAttribute("y", "100");
19        text.SetAttribute("font-family", "'Montserrat', sans-serif"); // custom font with fallback
20        text.SetAttribute("font-size", "36");
21        text.SetAttribute("fill", "#2c3e50");
22        text.TextContent = "Consistent Rendering Example";
23
24        document.RootElement.AppendChild(text);
25
26        // Initialize an instance of the ImageDevice class and specify an output file to render
27        IDevice device1 = new ImageDevice(new ImageRenderingOptions(), Path.Combine(OutputDir, "consistent-text.png"));
28        
29        // Render SVG to PNG
30        document.RenderTo(device1);
31
32        // Initialize an instance of the PdfDevice class and specify an output file to render
33        IDevice device2 = new PdfDevice(new PdfRenderingOptions(), Path.Combine(OutputDir, "consistent-text.pdf"));
34
35        // Render SVG to PDF
36        document.RenderTo(device2);
37    }
38}

Rendering Notes

  • Configuration ensures predictable font lookup: All text elements use the specified custom fonts before falling back to system fonts.
  • Consistent rendering across formats: The same SVG renders identically in PNG and PDF outputs.
  • Font fallback safety: Including a fallback font ensures text remains readable if the primary font is unavailable.
  • Inline style conflicts are avoided: Use normalized attributes or <style> to control font consistently.

This approach is essential for production scenarios, such as generating reports, certificates, or automated documents, where the SVG text must look identical on any machine.

Quick Font Handling Recipes

GoalRecommended ApproachNotes
Render SVG text identically on any serverEmbed fonts using @font-faceMakes SVG fully self-contained and platform-independent
Avoid unexpected Arial or default font fallbackSpecify a font-family list with a generic fallbackExample: 'CustomFont', sans-serif
Use custom fonts during SVG to image or PDF conversionConfigure FontsSettings via ConfigurationFont lookup folders are applied only at render time
Keep SVG portable across environmentsPrefer @font-face over server-side font lookupEmbedded fonts travel with the SVG file
Debug why a font is not appliedInspect inline styles and <tspan> elementsInline styles override global CSS rules
Ensure consistent text metrics after conversionUse the same font source for all outputsPrevents layout shifts caused by fallback fonts
Load fonts from relative paths in @font-faceSet a base URI when creating SVGDocumentRequired for resolving relative font URLs
ProblemReasonSolution
Font-family is applied but the text appearance does not changeInline styles or <tspan> elements override the parent <text> font settingsNormalize styles by updating <tspan> elements or removing conflicting inline font properties
SVG renders correctly in a browser but differently during conversionThe required font is not available in the conversion environmentEmbed the font using @font-face or provide it via FontsSettings
Arial or another default font appears unexpectedlyThe specified font cannot be resolved and no explicit fallback was definedAlways specify a font-family list with a generic fallback (e.g. sans-serif)
Custom font works during conversion but not inside the saved SVGFont lookup folders affect rendering only, not SVG portabilityUse @font-face to embed the font directly into the SVG
Font changes are ignored after loading an existing SVGExisting inline style attributes take precedence over global CSSModify or remove inline styles, or update font properties directly on the affected elements
Text renders with different metrics (spacing, size) after conversionDifferent fonts are used due to fallback or missing font filesEnsure the same font is resolved by embedding it or supplying a consistent font source
Relative font URLs do not work in @font-faceBase URI is missing or incorrectly setProvide a base URI when creating SVGDocument so relative font paths can be resolved

Related Resources

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.