Rule Builder – Create SVG CSS Rules in C#

SVG Style Rules in C#

SVG documents support CSS styling through the <style> element, allowing developers to apply reusable visual rules to SVG graphics. Using Aspose.SVG Builder API, you can configure SVG styles programmatically in C# without manually writing CSS strings.

This article explains how to create SVG style rules in C#, apply CSS selectors to SVG elements, configure custom fonts, and manage reusable SVG styles programmatically using Aspose.SVG for .NET.

What Is RuleBuilder?

RuleBuilder is part of the Aspose.SVG Builder API and is used to configure CSS declarations for SVG style rules programmatically. Together with SVGStyleElementBuilder, it allows developers to:

Using centralized CSS rules simplifies SVG maintenance and reduces duplicated styling code.

Create SVG Style Rules in C#

Aspose.SVG Builder API offers the SVGStyleElementBuilder class, which is an element builder for constructing an SVG <style> element. This class facilitates the creation and configuration of an SVG <style> element with CSS rules.

This example shows how to create an SVG <style> element, add a CSS rule @font-face to it, and use the AddRule() method to define font styles for text elements within an SVG document:

1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
 1// Configure an SVG document's style with external font-face rules in C# using Rule Builder
 2
 3// Initialize an SVG document
 4using (SVGDocument document = new SVGDocument())
 5{
 6    // Create an <svg> element and use Builder API to add other rules and elements to it
 7    SVGSVGElement svg = new SVGSVGElementBuilder()
 8        
 9       .AddDefs(def => def
10            .AddStyle(st => st
11                .Type("text/css")
12                .AddRule("@font-face", r => r
13                    .FontFamily("VeinlineRegular")
14                    .Attribute("src", "url(https://assets.ithillel.ua/wiki/VeinlineRegular.ttf)")
15                )
16                .AddRule("text", t => t
17                    .FontFamily("VeinlineRegular")
18                    .FontSize(30, LengthType.Pt)
19                )
20            )
21        )
22            .AddText(t => t
23            .X(20).Y(60).Fill(Color.DarkRed).FontWeight(FontWeight.Bold)
24            .AddContent("Configure SVG Style")
25            )
26            .AddText(t => t
27            .X(20).Y(150)
28            .AddContent("Set your SVG style with Rule Builder!")
29            )
30        .Build(document.FirstChild as SVGSVGElement);
31
32    // Save the SVG document
33    document.Save(Path.Combine(OutputDir, "font-face.svg"));
34}

font-face.svg file visualization

@font-face Rule

The @font-face CSS rule allows you to specify fonts that can be downloaded from a remote server or the user’s computer for displaying text within SVG graphics. This rule defines a custom font family name and specifies the source URL of the font file.

In the example above, the @font-face rule defines a custom font family named "VeinlineRegular". This rule ensures that the font is loaded and available for use within the SVG document.

AddRule() Method

The AddRule() method is part of the Rule Builder, which allows you to create CSS rules in SVG documents. It takes two parameters: the name of the CSS selector and a lambda expression defining the properties of the style using RuleBuilder.

In the C# example above, two rules are added:

Builders within Builders

SVG Builder API introduces syntactic sugar to further refine the process of SVG creation and manipulation. This includes nested builders for various SVG elements, providing a more intuitive and efficient way to define complex SVG structures. A “builder within a builder” pattern involves the use of multiple builder classes, where one builder is nested within another to facilitate the construction of complex objects or structures.

The following code snippet demonstrates how to use RuleBuilder, which is an example of a builder within a builder, to create and style SVG graphics programmatically:

1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
 1// Create SVG with styled circle and text elements using C# Rule Builder API and fluent syntax
 2
 3// Initialize an SVG document
 4using (SVGDocument document = new SVGDocument())
 5{
 6    // Create an <svg> element and use Builder API to add other rules and elements to it
 7    SVGSVGElement svg = new SVGSVGElementBuilder()
 8       
 9        .AddStyle(st => st
10            .AddRule("circle", r => r
11                .Fill(paint: Paint.None)
12                .Stroke(color: Color.DarkRed)
13                .StrokeWidth(60)
14            )
15            .AddRule("text", t => t
16                .Fill(color: Color.Red)
17                .Stroke(color: Color.Teal)
18                .StrokeWidth(1)
19                .FontFamily("Arial")
20                .FontSize(30, LengthType.Pt)
21            )
22        )
23        .AddG(g => g
24            .AddCircle(circle => circle.Cx(100).Cy(130).R(60).StrokeDashArray(2, 14))
25            .AddText("Rule Builder", x: 230, y: 140)
26        )
27        .Build(document.FirstChild as SVGSVGElement);
28
29    // Save the SVG document
30    document.Save(Path.Combine(OutputDir, "rule-builder.svg"));
31}

How the Style Rules Work

The AddRule() method creates reusable CSS rules inside the SVG <style> element. In this example:

This approach separates styling logic from SVG structure and improves SVG readability.

Common Mistakes and Fixes

ProblemPossible CauseRecommended Fix
SVG styles are not appliedIncorrect CSS selectorEnsure AddRule() targets the correct SVG element
Custom font is not displayedInvalid font URLVerify the font file path and accessibility
Text rendering differs between systemsThe required font is unavailableUse embedded or web-loaded fonts
SVG elements ignore style rulesInline attributes override CSSRemove conflicting inline styles
Stroke or fill styles are missingIncorrect style property configurationVerify Fill() and Stroke() rule settings

FAQ

1. Is RuleBuilder better than inline SVG styling?
For complex SVG graphics, reusable CSS rules are usually easier to maintain than repeated inline attributes. Rule Builder helps centralize SVG styling logic and reduce duplicated code.

2. Can I style SVG classes and IDs with RuleBuilder?
Yes. AddRule() supports standard CSS selectors, including element selectors, class selectors, and ID selectors.

3. Why use CSS rules inside SVG instead of external CSS files?
Embedded SVG styles make SVG graphics self-contained and easier to reuse across applications, exports, and standalone SVG files.

4. Can I reuse the same SVG style block for multiple elements?
Yes. A single SVG <style> block can apply reusable rules to multiple SVG elements using shared selectors.

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.