Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
SVG styling and font issues are among the most frequent problems developers encounter when rendering or converting SVG files. An image may look correct in a browser but render differently when converted to PDF or PNG, or programmatic style changes may have no effect.
Most issues are not bugs, but consequences of how SVG handles style resolution, inheritance, and font lookup. Inline styles, presentation attributes, and nested <tspan> elements often override global CSS silently, and missing fonts fall back to defaults without errors.
This article explains the root causes of common SVG styling and font problems in Aspose.SVG for .NET and provides practical C# solutions.
| Your Problem | Go To Section |
|---|---|
| CSS rules have no effect | CSS and Inline Styles Conflicts |
<tspan> ignores parent text styles | Mixed Styling Causes Unpredictable Rendering |
| Text always renders as Arial | Fonts Always Fall Back to Arial or Default |
| Works in browser, breaks in conversion | SVG Looks Correct in Browser but Breaks During Conversion |
Short answer: SVG styles are ignored because inline style attributes and presentation attributes override CSS rules by design. This most often happens when SVGs contain inline styles on elements or nested
SVG supports multiple ways to apply styles, but they have strict priority order (from highest to lowest):
style="fill:red; font-family:Arial;") – highest priority<style> element or external/programmatic CSS) – medium priorityfill="red", font-family="Arial") – lowest priorityWhen these methods are mixed (especially in SVGs exported from tools like Illustrator, Figma, Inkscape), CSS rules or programmatic changes often appear to be ignored. The most common reason is that inline style attributes on the element itself – or especially on nested child elements – override everything else.
Refer to the article SVG Styles: CSS vs Inline vs Attributes to learn more about CSS rules, inline styles, and presentation attributes.
style attribute and matching CSS rules → inline wins.<text> element has CSS or attributes applied, but nested <tspan> elements carry their own inline style → parent styles are completely ignored for that portion of text.Typical real-world example:
1<!-- Parent <text> style is IGNORED because <tspan> has inline style -->
2<text x="20" y="60" style="fill: black; font-size: 24px;">
3 <tspan style="fill: red; font-size: 40px;">This text is RED and 40px</tspan>
4</text>Even if you change font-family or fill on the <text> element programmatically, the <tspan> text will remain unchanged – because its inline styles take absolute precedence.
To make CSS reliable and programmatic changes effective, normalize the SVG by removing or cleaning conflicting inline styles. Choose one primary styling method (ideally CSS) and eliminate overrides.
Recommended Approach 1: Remove or Clean Inline style Attributes Globally
1using Aspose.Svg.Dom;
2using Aspose.Svg.Dom.Css;
3using System.IO; 1// Remove specific inline CSS properties that override SVG and stylesheet rules using Aspose.SVG for .NET
2
3SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
4var nodes = document.QuerySelectorAll("[style]");
5foreach (var node in nodes)
6{
7 if (node is IElementCSSInlineStyle styledElement)
8 {
9 ICSSStyleDeclaration style = styledElement.Style;
10 // Remove only properties that block CSS rules
11 style.RemoveProperty("fill");
12 style.RemoveProperty("stroke");
13 style.RemoveProperty("font-family");
14 style.RemoveProperty("font-size");
15
16 // Optional cleanup: remove empty style=""
17 if (style.Length == 0 && node is Element element)
18 {
19 element.RemoveAttribute("style");
20 }
21 }
22}
23document.Save(Path.Combine(OutputDir, "remove-inline-css-properties.svg"));After this, CSS from <style> blocks or applied via DOM will apply correctly and consistently.
Note: Unlike browser DOM APIs, Aspose.SVG does not expose inline styles directly on Element. To modify inline CSS, elements must be accessed through the IElementCSSInlineStyle interface.
Recommended Approach 2: Target Nested <tspan> Specifically (Most Common Fix)
1using Aspose.Svg.Dom;
2using System.Linq;
3using System.IO; 1// Normalize inline styles in nested SVG <tspan> elements to avoid unexpected text rendering using Aspose.SVG for .NET
2
3SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
4foreach (var node in document.QuerySelectorAll("tspan"))
5{
6 if (node is Element element && element.HasAttribute("style"))
7 {
8 var style = element.GetAttribute("style");
9
10 // Remove only conflicting properties
11 style = RemoveCssProperty(style, "fill");
12 style = RemoveCssProperty(style, "font-family");
13 style = RemoveCssProperty(style, "font-size");
14 if (string.IsNullOrWhiteSpace(style))
15 element.RemoveAttribute("style");
16 else
17 element.SetAttribute("style", style);
18 }
19}
20// --- Helper method ---
21static string RemoveCssProperty(string style, string property)
22{
23 if (string.IsNullOrWhiteSpace(style)) return string.Empty;
24 return string.Join("; ",
25 style.Split(';')
26 .Select(s => s.Trim())
27 .Where(s => !string.IsNullOrWhiteSpace(s) &&
28 !s.StartsWith(property + ":", StringComparison.OrdinalIgnoreCase))
29 ).TrimEnd(';');
30}
31document.Save(Path.Combine(OutputDir, "css-normalized.svg"));Alternative (Quick & Forceful): Apply styles directly as presentation attributes to both <text> and all <tspan>
1using Aspose.Svg.Dom;
2using System.IO; 1// Apply consistent presentation attributes to both SVG <text> and <tspan> elements using Aspose.SVG for .NET
2
3SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
4var nodes = document.QuerySelectorAll("text, tspan");
5foreach (var node in nodes)
6{
7 if (node is Element element)
8 {
9 element.SetAttribute("fill", "blue");
10 element.SetAttribute("font-family", "Arial");
11 element.SetAttribute("font-size", "20px");
12 }
13}
14document.Save(Path.Combine(OutputDir, "apply-presentation-attributes.svg"));Key Takeaway
If your CSS rules or code changes have no visible effect:
style attributes first (especially on <tspan>).Short answer: SVG text falls back to Arial or a default font because the specified font-family cannot be resolved at render time. In Aspose.SVG, this usually means the font was not explicitly registered via FontsSettings, was registered after the SVG was loaded, or the font-family value does not match the font’s internal family name.
By default, Aspose.SVG attempts to resolve fonts using system-installed fonts on the machine where rendering/conversion occurs. However, this behavior is not reliable across different environments (especially servers, containers, CI/CD pipelines, or headless machines), because:
font-family cannot be matched exactly (by internal family name), rendering silently falls back to a default font without throwing errors.To achieve consistent and predictable results on any machine (development, server, Docker, etc.), you should always explicitly register the required fonts using FontsSettings before loading the SVGDocument. This overrides unreliable system lookup and guarantees the same output everywhere.
Common reasons for fallback, even when you think the font is available:
FontsSettings.font-family value does not match the internal font family name (check in font metadata, not filename). 1using Aspose.Svg.Services;
2using System.IO;
3
4 var configuration = new Configuration();
5 var userAgent = configuration.GetService<IUserAgentService>();
6
7 // Register folder containing fonts
8 userAgent.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
9
10 var document = new SVGDocument(Path.Combine(DataDir, "input.svg"), configuration);
11 document.Save(Path.Combine(OutputDir, "output.svg"));
12
13 Console.WriteLine("SVG rendered with custom fonts successfully.");Do not use the font file name (Montserrat-Bold.ttf) in font-family. Use the internal font family name:
1font-family="Montserrat"Or with safe fallback chain:
1font-family="Montserrat, sans-serif"Aspose.SVG resolves fonts by family name, not by file name or path.
Short answer: SVG looks correct in browser but breaks during conversion because browsers load system and web fonts automatically, while Aspose.SVG requires explicit font registration.
Browser rendering and Aspose.SVG conversion differ fundamentally:
| Browser Rendering | Aspose.SVG Rendering |
|---|---|
| Uses system-installed fonts | Requires explicit font registration |
| Loads web fonts from URLs | Cannot access external URLs by default |
| Font fallback is automatic | Falls back to Arial if font not found |
| CSS from external files loads | External CSS may not resolve |
1<text x="20" y="60" style="font-family: 'Montserrat'; font-size: 32px;"> Browser-only font </text>This works in a browser if Montserrat is installed locally or loaded via CSS. During conversion, Aspose.SVG can only render this correctly if the font is explicitly available.
1using Aspose.Svg.Converters;
2using Aspose.Svg.Saving;
3using Aspose.Svg.Rendering.Image;
4using Aspose.Svg.Services;
5using System.IO; 1// Convert SVG text with a custom font using FontsSettings
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 userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
9
10 // Create SVG document with configuration
11 using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"), configuration))
12 {
13 // Convert SVG to JPG
14 ImageSaveOptions saveOptions = new ImageSaveOptions(ImageFormat.Jpeg);
15
16 Converter.ConvertSVG(document, saveOptions, Path.Combine(OutputDir, "ensuring-onversion-with-custom-font.jpg"));
17 }
18}In this example:
fonts directory must contain the required font files.Solution: Make SVG Self-Contained Before Conversion
This code registers custom fonts, optionally embeds them via @font-face in the SVG, and converts the document to PDF. It ensures that the output respects the intended font-family regardless of system-installed fonts or browser behavior.
1using Aspose.Svg.Converters;
2using Aspose.Svg.Saving;
3using Aspose.Svg.Services;
4using System.IO; 1// Embed fonts and make an SVG self-contained before converting it to PDF using Aspose.SVG for .NET
2
3// Register fonts
4var config = new Configuration();
5var userAgent = config.GetService<IUserAgentService>();
6userAgent.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
7
8// Load an SVG document
9var document = new SVGDocument(Path.Combine(DataDir, "input.svg"), config);
10
11// Embed font via @font-face (optional but recommended)
12var style = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
13style.TextContent = @"
14 @font-face {
15 font-family: 'Montserrat';
16 src: url('fonts/Montserrat-Italic.ttf') format('truetype');
17 }
18 text {
19 font-family: 'Montserrat', sans-serif;
20 }
21";
22document.RootElement.AppendChild(style);
23
24// Convert SVG to PDF
25var options = new PdfSaveOptions();
26Converter.ConvertSVG(document, options, Path.Combine(OutputDir, "output.pdf"));Key takeaway: Always register fonts explicitly and normalize styles for deterministic conversion.
Alternative: Convert Text to Paths
As an alternative to embedding or registering fonts, you can convert text elements to vector paths. This approach ensures that text appearance is preserved exactly, regardless of font availability, making the SVG fully self-contained and safe for conversion to PDF, PNG, or other formats.
1using System.IO;
2using Aspose.Svg.Saving; 1// Vectorize text elements in an SVG document using C#
2
3// Load an SVG document from file
4SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
5
6// Set text elements vectorization
7SVGSaveOptions saveOptions = new SVGSaveOptions
8{
9 VectorizeText = true
10};
11
12// Save the SVG document with specified saveOptions
13document.Save(Path.Combine(OutputDir, "text_vectorized.svg"), saveOptions);Before converting SVG to PDF, PNG, or other formats, verify these key points to ensure consistent rendering:
FontsSettings before creating the SVGDocument.style attributes on <text> or nested <tspan> elements that may override global styles.<tspan> Elements – Inspect child text elements for conflicting fill, font-family, or font-size styles; inline styles here always take priority over parent styles.Tip: Following this checklist guarantees predictable, deterministic rendering across different machines and formats when using Aspose.SVG for .NET.
1. Why does my SVG always fall back to Arial even when font-family is set?
Font fallback occurs when the specified font family cannot be resolved. This usually means the font was not registered via FontsSettings, was registered after loading the SVG, or the font-family value does not match the internal font family name.
2. Can I use Google Fonts or other web fonts with Aspose.SVG?
Aspose.SVG does not load fonts from external URLs at render time. To use web fonts, download the .ttf or .otf files locally and register them with FontsSettings before creating the
SVGDocument.
3. Why does removing all style attributes break my SVG?
Some inline styles control positioning, transforms, or non-visual properties. Instead of removing the entire style attribute, remove only conflicting properties such as fill, stroke, or font-family.
4. Can I force CSS to override inline styles?
Yes, but only if inline styles are removed or if CSS rules use !important. However, relying on !important is less predictable than normalizing or cleaning inline styles before rendering.
5. When should I convert SVG text to paths?
Convert text to paths when exact visual fidelity is required and font availability cannot be guaranteed. This approach removes all font dependencies but makes the text non-editable and increases SVG complexity.
| Symptom | Root Cause | Solution |
|---|---|---|
| Text renders as Arial | Font not registered | Register fonts BEFORE document load |
| CSS has no effect | Inline style attribute present | Remove conflicting properties from style |
<tspan> ignores parent | <tspan> has its own style | Remove styles from nested <tspan> elements |
| Works in Chrome, breaks in PDF | Relies on system/web fonts | Embed fonts via @font-face or register locally |
| Programmatic changes ignored | Style priority conflict | Use !important or remove inline styles |
@font-face with Aspose.SVG for .NET.Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.