Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
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.
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.
When an SVG document contains text, the rendering engine resolves fonts in the following order:
Explicit font declarations – Fonts defined directly on elements using:
font-family attributesstyle attributes<style>Embedded fonts – Fonts defined via @font-face inside the SVG document.
External or custom font sources – Fonts provided by the rendering engine, such as:
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 uses CSS syntax, but its font handling differs from HTML:
<tspan> styles have higher priority than global CSS rules.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.
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:
font-family values.@font-face or provide them via configuration.The following sections demonstrate these principles in practice using Aspose.SVG for .NET.
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.
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.'VeinlineRegular', sans-serif ensures a fallback if the embedded font fails.This example is particularly useful for scenarios where:
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.
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
SetFontsLookupFolder allows you to prioritize your own fonts before system fonts.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.
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
<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.
| Goal | Recommended Approach | Notes |
|---|---|---|
| Render SVG text identically on any server | Embed fonts using @font-face | Makes SVG fully self-contained and platform-independent |
| Avoid unexpected Arial or default font fallback | Specify a font-family list with a generic fallback | Example: 'CustomFont', sans-serif |
| Use custom fonts during SVG to image or PDF conversion | Configure FontsSettings via Configuration | Font lookup folders are applied only at render time |
| Keep SVG portable across environments | Prefer @font-face over server-side font lookup | Embedded fonts travel with the SVG file |
| Debug why a font is not applied | Inspect inline styles and <tspan> elements | Inline styles override global CSS rules |
| Ensure consistent text metrics after conversion | Use the same font source for all outputs | Prevents layout shifts caused by fallback fonts |
Load fonts from relative paths in @font-face | Set a base URI when creating SVGDocument | Required for resolving relative font URLs |
| Problem | Reason | Solution |
|---|---|---|
| Font-family is applied but the text appearance does not change | Inline styles or <tspan> elements override the parent <text> font settings | Normalize styles by updating <tspan> elements or removing conflicting inline font properties |
| SVG renders correctly in a browser but differently during conversion | The required font is not available in the conversion environment | Embed the font using @font-face or provide it via FontsSettings |
| Arial or another default font appears unexpectedly | The specified font cannot be resolved and no explicit fallback was defined | Always specify a font-family list with a generic fallback (e.g. sans-serif) |
| Custom font works during conversion but not inside the saved SVG | Font lookup folders affect rendering only, not SVG portability | Use @font-face to embed the font directly into the SVG |
| Font changes are ignored after loading an existing SVG | Existing inline style attributes take precedence over global CSS | Modify or remove inline styles, or update font properties directly on the affected elements |
| Text renders with different metrics (spacing, size) after conversion | Different fonts are used due to fallback or missing font files | Ensure the same font is resolved by embedding it or supplying a consistent font source |
Relative font URLs do not work in @font-face | Base URI is missing or incorrectly set | Provide a base URI when creating SVGDocument so relative font paths can be resolved |
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.