Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aspose-com-gists/32a415637339c7481de90dea9c87d34c to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-gists/32a415637339c7481de90dea9c87d34c to your computer and use it in GitHub Desktop.
This Gist contains C# examples Aspose.SVG for .NET – SVG Styles and Fonts Management

Working with SVG Text, Fonts, and Styles in C#

This Gist contains practical C# examples from the Aspose.SVG for .NET documentation demonstrating how to work with SVG text, fonts, and styles using Aspose.SVG for .NET. The examples focus on real-world scenarios where SVG text rendering behaves differently across browsers, image formats, and PDF output – and how to control that behavior programmatically.

What This Gist Covers

The code samples are grouped around two core topics:

1. Working with SVG Text and Fonts

Examples show how to:

  • Create and style <text> elements programmatically.
  • Render SVG text using custom fonts.
  • Configure font lookup folders for consistent rendering.
  • Apply font fallback for image and PDF conversions.
  • Embed fonts using @font-face (inline and programmatically).
  • Modify font-family of existing SVG text elements.
  • Ensure consistent text rendering across PNG, JPEG, and PDF outputs.

These scenarios are essential when:

  • system fonts are unavailable on the server
  • SVG looks correct in the browser but breaks during conversion
  • text layout changes between output formats

2. Working with SVG Styles and CSS

Examples demonstrate how to:

  • Apply global CSS styles to SVG text elements.
  • Remove or clean up conflicting inline styles.
  • Move presentation logic from inline attributes to <style> blocks.
  • Control CSS precedence for predictable rendering results.
  • Use DOM manipulation to normalize and enforce text styling.

These techniques help avoid common issues such as:

  • ignored CSS rules
  • unexpected inline overrides
  • inconsistent appearance after export

How to Use These Examples

  1. Ensure you have the Aspose.SVG for .NET library installed via NuGet.
  2. Clone or download this gist repository.
  3. Open any example in your preferred .NET IDE (Visual Studio, Rider, etc.).
  4. Adjust file paths, input, and output parameters as needed.
  5. Run the code to see the feature in action.

Prerequisites

  • .NET Framework 4.6.1+, .NET Core 2.0+, or .NET 5+.
  • Supported OS: Windows, Linux, macOS.
  • Visual Studio (or any .NET‑compatible IDE).
  • Aspose.SVG for .NET installed via NuGet.

About Aspose.SVG for .NET

Aspose.SVG for .NET is a powerful, on‑premise library designed to create, parse, manipulate, and convert SVG files. It provides a rich API for working with SVG DOM, applying styles, embedding fonts, and rendering to various output formats such as PNG, JPEG, PDF, and XPS.

Resources

Aspose.SVG for .NET – SVG Styling, Fonts and DOM Management
// Add a <style> element with CSS rules to an SVG document using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"));
// Create a new <style> element
SVGStyleElement styleElement = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
// Define CSS rules for text elements
styleElement.TextContent = "text { font-family: 'DejaVu Sans', sans-serif; font-size: 36px; fill: #1abc9c; }";
// Append the style element to the SVG root
document.RootElement.AppendChild(styleElement);
// Save the modified SVG document
document.Save(Path.Combine(OutputDir, "css-styles.svg"));
// Apply inline CSS styles to existing SVG <text> elements using C#
// Learn more: https://docs.aspose.com/svg/net/
// Load an existing SVG document containing text elements
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"));
// Select the first <text> element
SVGTextElement text = document.QuerySelector("text") as SVGTextElement;
// Apply inline CSS styles to the text element
if (text != null)
{
// Set the style attribute directly
text.SetAttribute("style", "font-size: 36px; fill: #034586;");
}
// Save the modified SVG document
document.Save(Path.Combine(OutputDir, "inline-styles.svg"));
// Apply presentation attributes (fill, font-size, font-family) to SVG <text> elements using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"));
// Select the first <text> element in the document
SVGTextElement text = document.QuerySelector("text") as SVGTextElement;
if (text != null)
{
// Apply presentation attributes directly to the element
text.SetAttribute("fill", "#2c3e50");
text.SetAttribute("font-size", "36");
text.SetAttribute("font-family", "Open Sans");
}
// Save the modified SVG document
document.Save(Path.Combine(OutputDir, "presentation-attributes.svg"));
// Apply consistent presentation attributes to both SVG <text> and <tspan> elements using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
var nodes = document.QuerySelectorAll("text, tspan");
foreach (var node in nodes)
{
if (node is Element element)
{
element.SetAttribute("fill", "blue");
element.SetAttribute("font-family", "Arial");
element.SetAttribute("font-size", "20px");
}
}
document.Save(Path.Combine(OutputDir, "apply-presentation-attributes.svg"));
// Convert SVG text with a custom font using FontsSettings
// Learn more: https://docs.aspose.com/svg/net/
// Create an instance of the Configuration class
using (Configuration configuration = new Configuration())
{
// Configure custom fonts folder
IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
// Create SVG document with configuration
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"), configuration))
{
// Convert SVG to JPG
ImageSaveOptions saveOptions = new ImageSaveOptions(ImageFormat.Jpeg);
Converter.ConvertSVG(document, saveOptions, Path.Combine(OutputDir, "ensuring-onversion-with-custom-font.jpg"));
}
}
// Create and style an SVG <text> element programmatically using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
// Create a new SVG document
var document = new SVGDocument();
// Access the root <svg> element
SVGSVGElement svg = document.RootElement;
svg.SetAttribute("width", "600");
svg.SetAttribute("height", "200");
// Create a new <text> element
var text = document.CreateElementNS("http://www.w3.org/2000/svg", "text");
text.SetAttribute("x", "50");
text.SetAttribute("y", "100");
text.SetAttribute("font-family", "Arial");
text.SetAttribute("font-size", "24");
text.SetAttribute("fill", "blue");
text.TextContent = "Working with SVG Text";
// Append text to SVG
svg.AppendChild(text);
// Initialize ImageSaveOptions
ImageSaveOptions saveOptions = new ImageSaveOptions(ImageFormat.Jpeg);
// Convert SVG to JPG
Converter.ConvertSVG(document, saveOptions, Path.Combine(OutputDir, "basic-text.jpg"));
// Find and inspect SVG elements that use inline style attributes with Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg"));
// Select all elements that have inline style attributes
var styledNodes = document.QuerySelectorAll("[style]");
Console.WriteLine($"Found {styledNodes.Length} element(s) with inline styles:\n");
foreach (var node in styledNodes)
{
var element = (Element)node;
// Get and display the style attribute value
string styleValue = element.GetAttribute("style");
Console.WriteLine($"Element: <{element.TagName}>");
Console.WriteLine($"Style: {styleValue}\n");
}
// Embed fonts and make an SVG self-contained before converting it to PDF using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
// Register fonts
var config = new Configuration();
var userAgent = config.GetService<IUserAgentService>();
userAgent.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
// Load an SVG document
var document = new SVGDocument(Path.Combine(DataDir, "input.svg"), config);
// Embed font via @font-face (optional but recommended)
var style = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
style.TextContent = @"
@font-face {
font-family: 'Montserrat';
src: url('fonts/Montserrat-Italic.ttf') format('truetype');
}
text {
font-family: 'Montserrat', sans-serif;
}
";
document.RootElement.AppendChild(style);
// Convert SVG to PDF
var options = new PdfSaveOptions();
Converter.ConvertSVG(document, options, Path.Combine(OutputDir, "output.pdf"));
// Normalize inline styles in nested SVG <tspan> elements to avoid unexpected text rendering using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
foreach (var node in document.QuerySelectorAll("tspan"))
{
if (node is Element element && element.HasAttribute("style"))
{
var style = element.GetAttribute("style");
// Remove only conflicting properties
style = RemoveCssProperty(style, "fill");
style = RemoveCssProperty(style, "font-family");
style = RemoveCssProperty(style, "font-size");
if (string.IsNullOrWhiteSpace(style))
element.RemoveAttribute("style");
else
element.SetAttribute("style", style);
}
}
// --- Helper method ---
static string RemoveCssProperty(string style, string property)
{
if (string.IsNullOrWhiteSpace(style)) return string.Empty;
return string.Join("; ",
style.Split(';')
.Select(s => s.Trim())
.Where(s => !string.IsNullOrWhiteSpace(s) &&
!s.StartsWith(property + ":", StringComparison.OrdinalIgnoreCase))
).TrimEnd(';');
}
document.Save(Path.Combine(OutputDir, "css-normalized.svg"));
// Remove specific inline CSS properties that override SVG and stylesheet rules using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
var nodes = document.QuerySelectorAll("[style]");
foreach (var node in nodes)
{
if (node is IElementCSSInlineStyle styledElement)
{
ICSSStyleDeclaration style = styledElement.Style;
// Remove only properties that block CSS rules
style.RemoveProperty("fill");
style.RemoveProperty("stroke");
style.RemoveProperty("font-family");
style.RemoveProperty("font-size");
// Optional cleanup: remove empty style=""
if (style.Length == 0 && node is Element element)
{
element.RemoveAttribute("style");
}
}
}
document.Save(Path.Combine(OutputDir, "remove-inline-css-properties.svg"));
// Remove all inline style attributes from an SVG to prevent CSS conflicts
// Learn more: https://docs.aspose.com/svg/net/
// Load an existing SVG document
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
// Select all elements that have inline style attributes
var nodes = document.QuerySelectorAll("[style]");
// Iterate through all styled elements
foreach (var node in nodes)
{
// Cast node to Element and remove the style attribute
if (node is Element element)
{
element.RemoveAttribute("style");
}
}
// Save the modified SVG document without inline styles
document.Save(Path.Combine(OutputDir, "inline-styles-removed.svg"));
// Render SVG text with a custom font using FontsSettings in Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
// Create an instance of the Configuration class
using (Configuration configuration = new Configuration())
{
// Configure custom fonts folder
IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
// Create SVG document WITH configuration
using (SVGDocument document = new SVGDocument(configuration))
{
// Create <text> element
SVGTextElement text = (SVGTextElement)document.CreateElementNS("http://www.w3.org/2000/svg", "text");
text.SetAttribute("x", "50");
text.SetAttribute("y", "100");
text.SetAttribute("font-family", "Montserrat");
text.SetAttribute("font-size", "24");
text.TextContent = "Custom Font Example";
document.RootElement.AppendChild(text);
// Convert SVG to JPG
ImageSaveOptions saveOptions = new ImageSaveOptions(ImageFormat.Jpeg);
Converter.ConvertSVG(document, saveOptions, Path.Combine(OutputDir, "custom-font.jpg"));
}
}
// Safely remove specific inline CSS properties and replace them with SVG attributes using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"));
// Select elements that contain inline styles
var nodes = document.QuerySelectorAll("[style]");
foreach (var node in nodes)
{
var element = (Element)node;
// Read inline style as plain text
var style = element.GetAttribute("style");
if (string.IsNullOrEmpty(style))
continue;
// Remove only fill-related declarations
var cleanedStyle = RemoveStyleProperty(style, "fill");
if (string.IsNullOrWhiteSpace(cleanedStyle))
{
// Remove empty style attribute
element.RemoveAttribute("style");
}
else
{
element.SetAttribute("style", cleanedStyle);
}
// Apply deterministic presentation attribute
element.SetAttribute("fill", "#FF7A00");
}
// Save the modified SVG document
document.Save(Path.Combine(OutputDir, "style-normalized.svg"));
// --- Helper method ---
static string RemoveStyleProperty(string style, string property)
{
var declarations = style.Split(';');
var result = new List<string>();
foreach (var decl in declarations)
{
if (!decl.TrimStart().StartsWith(property + ":", StringComparison.OrdinalIgnoreCase))
{
result.Add(decl.Trim());
}
}
return string.Join("; ", result);
}
// Select all SVG shape elements and apply a uniform fill color using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg"));
// Select common shape elements
var shapes = document.QuerySelectorAll("path, rect, circle, ellipse, polygon");
foreach (var node in shapes)
{
var element = (Element)node;
element.SetAttribute("fill", "#FF7A00");
}
// Save the modified SVG document
document.Save(Path.Combine(OutputDir, "shapes-colored.svg"));
// How to apply CSS styling to SVG text elements and clean up inline styles using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg"));
var nodes = document.QuerySelectorAll("[style]");
foreach (var node in nodes)
{
var element = (Element)node;
var style = element.GetAttribute("style");
if (string.IsNullOrEmpty(style))
continue;
// Remove only fill-related declarations
var cleanedStyle = RemoveStyleProperty(style, "fill");
if (string.IsNullOrWhiteSpace(cleanedStyle))
{
element.RemoveAttribute("style");
}
else
{
element.SetAttribute("style", cleanedStyle);
}
}
// Create global <style> element
SVGStyleElement style1 = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
style1.SetAttribute("type", "text/css");
style1.TextContent =
"text { " +
"font-family: 'DejaVu Sans', sans-serif; " +
"font-size: 16px; " +
"fill: red; " +
"}";
// Insert style at the top of SVG
SVGSVGElement root = document.RootElement;
root.InsertBefore(style1, root.FirstChild);
// Save result
document.Save(Path.Combine(OutputDir, "styled-text-css.svg"));
// Helper method to remove specific CSS property from style string
static string RemoveStyleProperty(string style, string property)
{
// Split style string into individual declarations
var declarations = style.Split(';');
var result = new List<string>();
// Filter out declarations that start with the target property
foreach (var decl in declarations)
{
if (!decl.TrimStart().StartsWith(property + ":", StringComparison.OrdinalIgnoreCase))
{
result.Add(decl.Trim());
}
}
// Rebuild style string
return string.Join("; ", result);
}
// Apply global CSS styles to SVG text elements after removing conflicting inline styles using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
// Load SVG document
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "text.svg")))
{
// Select all text-related elements
var textNodes = document.QuerySelectorAll("text, tspan");
// Remove inline style attributes
for (int i = 0; i < textNodes.Length; i++)
{
Element element = textNodes[i] as Element;
if (element != null && element.HasAttribute("style"))
{
element.RemoveAttribute("style");
}
}
// Create global <style> element
SVGStyleElement style = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
style.SetAttribute("type", "text/css");
style.TextContent =
"text { " +
"font-family: 'DejaVu Sans', sans-serif; " +
"font-size: 16px; " +
"fill: #2c3e50; " +
"}";
// Insert style at the top of SVG
SVGSVGElement root = document.RootElement;
root.InsertBefore(style, root.FirstChild);
// Save result
document.Save(Path.Combine(OutputDir, "styled-text.svg"));
}
// Ensure consistent SVG text rendering across PNG and PDF outputs using custom fonts
// Learn more: https://docs.aspose.com/svg/net/
// Create configuration to specify custom fonts folder
using (Configuration configuration = new Configuration())
{
IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
// Set folder containing your custom fonts
userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
// Create SVG document with configuration
using (SVGDocument document = new SVGDocument(configuration))
{
// Create <text> element
SVGTextElement text = (SVGTextElement)document.CreateElementNS("http://www.w3.org/2000/svg", "text");
text.SetAttribute("x", "50");
text.SetAttribute("y", "100");
text.SetAttribute("font-family", "'Montserrat', sans-serif"); // custom font with fallback
text.SetAttribute("font-size", "36");
text.SetAttribute("fill", "#2c3e50");
text.TextContent = "Consistent Rendering Example";
document.RootElement.AppendChild(text);
// Initialize an instance of the ImageDevice class and specify an output file to render
IDevice device1 = new ImageDevice(new ImageRenderingOptions(), Path.Combine(OutputDir, "consistent-text.png"));
// Render SVG to PNG
document.RenderTo(device1);
// Initialize an instance of the PdfDevice class and specify an output file to render
IDevice device2 = new PdfDevice(new PdfRenderingOptions(), Path.Combine(OutputDir, "consistent-text.pdf"));
// Render SVG to PDF
document.RenderTo(device2);
}
}
// How to embed external font into SVG using @font-face and convert to PDF with Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
// SVG content with embedded @font-face
string svgContent =
@"<svg xmlns='http://www.w3.org/2000/svg' width='600' height='140'>
<style>
@font-face {
font-family: 'VeinlineRegular';
src: url(https://assets.ithillel.ua/wiki/VeinlineRegular.ttf);
}
text {
font-family: 'EmbeddedFont';
font-size: 28px;
fill: #2b2b2b;
}
</style>
<text x='40' y='90'>
SVG text rendered with @font-face
</text>
</svg>";
// Create SVG document with base URI
using (SVGDocument document = new SVGDocument(svgContent, DataDir))
{
PdfSaveOptions pdfOptions = new PdfSaveOptions();
// Convert SVG to PDF
Converter.ConvertSVG(document, pdfOptions, Path.Combine(OutputDir, "svg-font-face.pdf"));
}
// Embed custom fonts into SVG using @font-face programmatically and convert to PDF with Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
// Create SVG document
using (SVGDocument document = new SVGDocument())
{
SVGSVGElement root = document.RootElement;
// Create <style> element
SVGStyleElement style = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
style.SetAttribute("type", "text/css");
// Define @font-face rule programmatically
style.TextContent =
"@font-face { " +
" font-family: 'VeinlineRegular'; " +
" src: url(https://assets.ithillel.ua/wiki/VeinlineRegular.ttf); " +
"} " +
"text { " +
" font-family: 'VeinlineRegular', sans-serif; " +
" font-size: 28px; " +
" fill: #2c3e50; " +
"}";
// Append <style> to SVG root
root.AppendChild(style);
// Create <text> element
SVGTextElement text = (SVGTextElement)document.CreateElementNS("http://www.w3.org/2000/svg", "text");
text.SetAttribute("x", "40");
text.SetAttribute("y", "90");
text.TextContent = "SVG text rendered with @font-face";
root.AppendChild(text);
// Convert SVG to PDF
PdfSaveOptions pdfOptions = new PdfSaveOptions();
Converter.ConvertSVG(document, pdfOptions, Path.Combine(OutputDir, "svg-font-face.pdf"));
}
// Render SVG text to PDF with font fallback when custom fonts are unavailable using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
// Create configuration and specify custom fonts directory
using (Configuration configuration = new Configuration())
{
IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
// Load existing SVG document
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "input.svg"), configuration))
{
// Find the first <text> element in the document
SVGTextElement text = document.QuerySelector("text") as SVGTextElement;
if (text != null)
{
// Set custom font with fallback
text.SetAttribute("font-family", "'Montserrat', sans-serif");
}
document.Save(Path.Combine(OutputDir, "font-fallback.svg"));
// Convert SVG to PNG
ImageSaveOptions saveOptions = new ImageSaveOptions();
Converter.ConvertSVG(document, saveOptions, Path.Combine(OutputDir, "font-fallback.png"));
}
}
// Render SVG text to PDF with font fallback when custom fonts are unavailable using Aspose.SVG for .NET
// Learn more: https://docs.aspose.com/svg/net/
using (Configuration configuration = new Configuration())
{
// Configure custom fonts directory
IUserAgentService userAgentService = configuration.GetService<IUserAgentService>();
userAgentService.FontsSettings.SetFontsLookupFolder(Path.Combine(DataDir, "fonts"));
// Create SVG document with configuration
using (SVGDocument document = new SVGDocument(configuration))
{
// Create <style> with font fallback
SVGStyleElement style = (SVGStyleElement)document.CreateElementNS("http://www.w3.org/2000/svg", "style");
style.TextContent =
"text { font-family: 'Montserrat', sans-serif; " +
"font-weight: bold " +
"font-size: 26px; fill: #2c2c2c; }";
document.RootElement.AppendChild(style);
// Create text element
SVGTextElement text = (SVGTextElement)document.CreateElementNS("http://www.w3.org/2000/svg", "text");
text.SetAttribute("x", "40");
text.SetAttribute("y", "80");
text.TextContent = "Font fallback PDF example";
document.RootElement.AppendChild(text);
document.Save(Path.Combine(OutputDir, "font-fallback.svg"));
PdfSaveOptions pdfOptions = new PdfSaveOptions();
// Convert SVG to PDF
Converter.ConvertSVG(document, pdfOptions, Path.Combine(OutputDir, "font-fallback.pdf"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment