Element Builders – Create SVG Elements in C# with Fluent Builder API

Aspose.SVG Builder API allows developers to create and edit SVG elements programmatically in C# using fluent builder syntax. Instead of manually constructing SVG XML or manipulating DOM attributes directly, Element Builders provide a cleaner and more maintainable approach to SVG generation.

The Builder API supports common SVG elements such as rectangles, circles, paths, lines, polygons, text, and groups. Using nested builders and chained methods, developers can generate complex SVG graphics with less boilerplate code and improved readability.

This article explains how to create SVG elements in C#, build SVG graphics programmatically, and modify existing SVG documents using Aspose.SVG for .NET. You will learn about the SVGElementBuilder base class, the SVGSVGElementBuilder class, specialized element builders, and how they simplify SVG programming.

What Are SVG Element Builders?

Element Builders are specialized builder classes used to create SVG elements programmatically. Each builder corresponds to a specific SVG element and provides strongly typed methods for configuring SVG attributes and styles.

The Builder API supports:

Using fluent syntax simplifies SVG generation and improves code maintainability in .NET applications.

Supported SVG Element Builders

BuilderSVG Element
SVGSVGElementBuilder<svg>
SVGRectElementBuilder<rect>
SVGCircleElementBuilder<circle>
SVGLineElementBuilder<line>
SVGPathElementBuilder<path>
SVGTextElementBuilder<text>
SVGGElementBuilder<g>
SVGPolygonElementBuilder<polygon>
SVGPolylineElementBuilder<polyline>

You will find a complete list of SVG element builders on the API Reference Aspose.Svg.Builder page.

Creating New Elements

Aspose.SVG SVG Builder API employs the Fluent Builder Pattern, a design methodology that aligns perfectly with the need for simplicity, clarity, and versatility in SVG manipulation.

Fluent Builder Pattern

In the SVG Builder API the Fluent Builder Pattern is used to simplify the creation and updating of SVG elements, making the process intuitive and less error-prone. The essence of this pattern is methods that configure an SVG element and return the builder instance for method chaining. This design provides a consistent and coherent way to link methods, which is especially effective at reducing the complexity associated with creating and managing SVG elements.

In this context, lambda expressions are used to improve the clarity and conciseness of the builder’s configuration methods. Lambda expressions allow you to define the attributes and styles of SVG elements in a detailed yet compact way. For example, when adding a circle element, the lambda expression provides an inline readable configuration:

1    using (SVGDocument document = new SVGDocument())
2    {
3        SVGSVGElement svgElement = new SVGSVGElementBuilder()
4            .AddCircle(circle => circle
5                .Cx(100).Cy(100).R(50)
6                .Fill(Color.Red).Stroke(Paint.None)
7                .StrokeWidth(2))
8            .Build(document);
9    }

Here, circle => circle.Cx(100).Cy(100).R(50).Fill(Color.Red).Stroke(Paint.None).StrokeWidth(2) is a succinct way to configure the circle’s properties, such as its center, radius, fill, and stroke. This approach not only simplifies the element configuration but also enhances the code’s readability and maintainability.

Create SVG from Scratch

Here, we will explore a concise and elegant approach to crafting SVGs from scratch using C#.

1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
 1    // Create SVG from scratch in C# using Builder API
 2
 3    // Create an <svg> element with specified width, height and viewBox, and add into it other required elements
 4    SVGSVGElement svg = new SVGSVGElementBuilder()
 5        .Width(700).Height(300)
 6        .ViewBox(0, 0, 700, 300)
 7
 8        .AddG(g => g
 9        .AddCircle(circle => circle.Cx(130).Cy(130).R(60).Fill(Paint.None).Stroke(Color.FromArgb(200, 0, 0)).StrokeWidth(70).StrokeDashArray(2, 14))
10        .AddText("I can create SVG from scratch!", x: 270, y: 140, fontSize: 30, fill: Color.Teal)
11        )
12        .Build(document.FirstChild as SVGSVGElement);
13
14    // Save the document
15    document.Save(Path.Combine(OutputDir, "svg-from-scratch.svg"));
16}

svg-from-scratch.svg file visualization

The example utilizes a Fluent Builder Pattern within SVGSVGElementBuilder to construct the SVG elements. This pattern provides an expressive and maintainable way to generate SVG documents compared to the approach described in the Edit SVG File article, which relies more on low-level DOM manipulation and explicit attribute setting. This approach:

Editing SVG

One powerful technique for programmatically editing SVGs is through the use of Element Builders.

Adding New Elements

Editing SVGs using element builders provides a powerful and flexible approach to manipulating vector graphics programmatically. In the following example, we take an existing SVG file, add some elements to it, and save it:

1using Aspose.Svg.Builder;
2using System.Drawing;
3using System.IO;
 1// Add multiple shapes (circle and polyline) to an existing SVG document using SVG Builder
 2
 3string documentPath = Path.Combine(DataDir, "circles.svg");
 4
 5// Initialize an SVG document
 6using (SVGDocument document = new SVGDocument(documentPath))
 7{
 8    // Create a <circle> element with attributes
 9    SVGCircleElement circle = new SVGCircleElementBuilder()
10     .Cx(350).Cy(70).R(50).Fill(Paint.None).Stroke(Color.FromArgb(80, 132, 132)).StrokeWidth(10)
11     .Build(document);
12
13    // Append the newly created <circle> element to the root <svg> element
14    document.RootElement.AppendChild(circle);
15
16    // Create a <polyline> element with attributes
17    SVGPolylineElement polyline = new SVGPolylineElementBuilder()
18    .Points(new double[] { 125, 130, 275, 180, 425, 130 }).Stroke(Color.FromArgb(80, 132, 132)).Fill(Paint.None).StrokeWidth(10)
19    .Build(document);
20
21    // Append the newly created <polyline> element to the root <svg> element
22    document.RootElement.AppendChild(polyline);
23
24    // Save the document
25    document.Save(Path.Combine(OutputDir, "circles-edited.svg"));
26}

In this example:

Figure (a) shows a visualization of the original circles.svg file, and figure (b) shows an image of the edited circles-edited.svg file with added circle and polyline elements.

Visualization of the original circles.svg file and the edited circles-edited.svg file with added circle and polyline elements.

Modifying Existing Elements

In the following C# example, we update an existing SVG document by changing the fill and stroke color of the first SVG <circle> element in the document:

1using Aspose.Svg;
2using Aspose.Svg.Builder;
3using System.Drawing;
4using Aspose.Svg.Dom.Svg;
5using System.Linq;
6using System.IO;
 1// Modify an existing SVG element in C# using SVG Builder
 2
 3string documentPath = Path.Combine(DataDir, "circles.svg");
 4
 5// Initialize an SVG document
 6using (SVGDocument document = new SVGDocument(documentPath))
 7{
 8    // Assume an existing SVG element is part of the document
 9    SVGCircleElement circle = document.GetElementsByTagName("circle").First() as SVGCircleElement;
10
11    // Modify the first <circle> element using SVGCircleElementBuilder
12    new SVGCircleElementBuilder()
13        .Stroke(Color.DarkRed).Fill(Color.LightGray)
14
15        // The first <circle> element is now updated with new configurations
16        .Build(circle);
17
18    // Save the document
19    document.Save(Path.Combine(OutputDir, "circles-modified.svg"));
20}

Element builders offer the Build(T element) method for updating existing SVG elements, allowing modifications to their attributes or styles. Figure (a) shows the original circles.svg file, and figure (b) shows an image of the modified circles-modified.svg file with the recolored first circle element.

Visualization of the original circles.svg file and the modified circles-modified.svg file with the recolored first circle element.

Example of Using Element Builders

The following code snippet shows how to use element builders to create an SVG document with various SVG shape elements.

1using Aspose.Svg;
2using Aspose.Svg.Builder;
3using System.Drawing;
4using Aspose.Svg.Dom.Svg;
5using System.IO;
 1// Create all basic SVG shapes programmatically in C# using SVG Builder
 2
 3string svgContent = "<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
 4using (SVGDocument document = new SVGDocument(svgContent, "."))
 5{
 6    SVGSVGElement svg = new SVGSVGElementBuilder()
 7        .Width(100, LengthType.Percentage).Height(100, LengthType.Percentage)
 8        .ViewBox(0, 0, 800, 800)
 9
10            .AddG(g => g.FontSize(20).TextAnchor(TextAnchor.End)
11                .AddText("<rect>", y: 30)
12                .AddText("<circle>", y: 70)
13                .AddText("<ellipse>", y: 110)
14                .AddText("<line>", y: 150)
15                .AddText("<polyline>", x: 300, y: 30)
16                .AddText("<polygon>", x: 300, y: 70)
17                .AddText("<path>", x: 300, y: 110)
18                )
19
20            .AddG(gg => gg.Fill(Color.Teal).StrokeWidth(3)
21                .AddRect(r => r.X(35).Y(5).Width(30).Height(30))
22                .AddCircle(c => c.Cx(50).Cy(60).R(17))
23                .AddEllipse(e => e.Cx(50).Cy(100).Rx(25).Ry(12))
24                .AddLine(l => l.X1(30).X2(70).Y1(140).Y2(140).Stroke(Color.Teal))
25                )
26            .AddG(ggg => ggg.Fill(Paint.None).StrokeWidth(3).Stroke(Color.Teal).Transform(t => t.Translate(300, -160))
27                .AddPolygon(points: new double[] { 30, 215, 90, 215, 120, 230, 70, 240, 30, 215 }, fill: Color.Teal)
28                .AddPolyline(points: new double[] { 30, 200, 65, 170, 90, 190, 120, 180 })
29                .AddPath(d: path => path.M(30, 275).Q(55, 250, 70, 250).T(80, 275).T(120, 260))
30                )
31
32        .Build(document.FirstChild as SVGSVGElement);
33    document.Save(Path.Combine(OutputDir, "svg-elements.svg"));
34}

Visualization of the svg-elements.svg file with names and images of the 7 shape SVG elements.

Element builders provide a fluent and expressive syntax for constructing SVG elements, enhancing code readability and maintainability. In this example, the SVGSVGElementBuilder is employed to construct an SVG element with width, height, and viewBox attributes. The Fluent Builder Pattern is then used to create shapes like rectangles, circles, ellipses, lines, polylines, polygons, and paths, each positioned and styled accordingly within <g> elements.

Why Use Fluent SVG Builders?

DOM ManipulationBuilder API
Manual attribute handlingStrongly typed methods
More verbose codeFluent chained syntax
Harder to maintainEasier to read
Repeated XML operationsReusable builder logic

FAQ

1. Why do developers use Builder APIs instead of direct XML generation?
Builder APIs simplify SVG creation by replacing manual XML construction with typed fluent methods, making SVG code easier to read, maintain, and extend.

2. Is the generated SVG standards-compliant?
Yes. Aspose.SVG generates standards-based SVG markup compatible with modern SVG rendering engines.

3. Can I generate interactive SVG graphics with Element Builders?
Yes. Generated SVG elements can later be styled, animated, or manipulated with CSS and JavaScript in web applications.

4. Can generated SVG graphics be embedded directly into HTML pages?
Yes. SVG documents created with Aspose.SVG can be embedded inline into HTML or used as standalone SVG files in web applications.

Common Mistakes and Fixes

ProblemPossible CauseRecommended Fix
SVG element is not visibleMissing fill or strokeApply Fill() or Stroke() styles
SVG changes are not savedDocument was not saved after modificationCall document.Save() after updates
Elements appear outside the canvasIncorrect coordinates or viewBoxVerify SVG dimensions and positions
Existing element is not updatedIncorrect element referenceEnsure the target SVG element is retrieved correctly
Shapes appear distortedInvalid viewBox proportionsUse consistent SVG coordinate systems

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.