Create SVG, Load and Read SVG in C#

To perform any task, you must create or load a document. Aspose.SVG for .NET API lets you construct an SVG document from scratch as well as load an existing SVG from different sources. The API provides SVGDocument class that has several constructors allowing you to produce new class instances. The SVGDocument is the root of the SVG DOM hierarchy, holds the entire content and is entirely based on W3C SVG 2.0 and WHATWG DOM specifications.

SVG files can be created & loaded:

This article provides some examples of creating & loading SVG files using Aspose.SVG for .NET API. The SVGDocument has a wide set of overloaded constructors allowing you to create a blank document or load it from a file, URL, stream, etc.

Create an Empty SVG Document

Aspose.SVG for .NET API provides the SVGDocument class that can be used to create an empty document using its default constructor. Once the document object is created, it can be filled later with SVG elements. The following C# code snippet shows the usage of the default SVGDocument() constructor to create an SVG document.

1using Aspose.Svg;
2...
3
4    // Initialize an empty SVG document
5    using (var document = new SVGDocument())
6    {
7        // Work with the SVG document here...
8    }

If you want to save created empty SVG document to a file, use the following C# code snippet:

 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    // Prepare output path for a document saving
 6    string documentPath = Path.Combine(OutputDir, "empty.svg");
 7
 8	// Initialize an empty SVG document
 9	using (var document = new SVGDocument())
10	{
11	    // Work with the SVG document here...
12
13	    // Save the document to a file
14	    document.Save(documentPath);
15	}

More details about SVG file saving are in the Save an SVG Document section. In the article Edit SVG File, you learn how to edit SVG using Aspose.SVG for .NET library and find detailed examples of how to add new elements to SVG documents and apply SVG filters to bitmaps.

Create SVG from a Memory String

You can create SVG from a string content using SVGDocument (string, string) constructor. If your case is to produce a document from a user string directly in your code and you don’t need to save it to a file, the following example could help you: we produce an SVG document that contains a circle with a radius of 40 pixels.

 1using Aspose.Svg;
 2...
 3
 4    // Prepare SVG code
 5    var documentContent = "<svg xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"50\" cy=\"50\" r=\"40\" /></svg>";	
 6
 7	// Initialize an SVG document from a string content
 8	using (var document = new SVGDocument(documentContent, "."))
 9	{
10	    // Work with the document here...
11	}

Create SVG from a Stream

To create SVG from a stream, use one of SVGDocument() constructors:

 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    //Prepare a path to a file required for a FileStream object creating
 6    string documentPath = Path.Combine(DataDir, "bezier-curves.svg");
 7
 8	// Create a FileStream object
 9	using (var stream = new FileStream(documentPath, FileMode.Open, FileAccess.Read))
10	{
11	    // Initialize an SVG document from the stream
12		using (var document = new SVGDocument(stream, "."))
13	    {
14	        // Work with the document
15	    }
16	}

Create Custom SVG Documents Using SVG Builder API

The SVG Builder API offers a powerful and flexible way to programmatically construct SVG documents. By leveraging the SVGSVGElementBuilder class, developers can easily create complex SVG graphics with detailed customization options. For more information on utilizing the SVG Builder API, refer to the documentation article Advanced SVG Creation and Modification with Aspose.SVG Builder API.

Here’s an example demonstrating how to create a custom SVG document featuring various graphic elements:

 1using Aspose.Svg;
 2using Aspose.Svg.Builder;
 3using System.Drawing;
 4...
 5
 6    // Initialize an SVG document
 7    using (var document = new SVGDocument())
 8    {
 9        // Create an <svg> element with specified width, height and viewBox, and add into it other required elements
10        var svg = new SVGSVGElementBuilder()
11            .Width(100).Height(100)
12            .ViewBox(-21, -21, 42, 42)
13            .AddDefs(def => def
14                .AddRadialGradient(id: "b", cx: .2, cy: .2, r: .5, fx: .2, fy: .2, extend: ev => ev
15                    .AddStop(offset: 0, stopColor: Color.FromArgb(0xff, 0xff, 0xFF), stopOpacity: .7)
16                    .AddStop(offset: 1, stopColor: Color.FromArgb(0xff, 0xff, 0xFF), stopOpacity: 0)
17                )
18                .AddRadialGradient(id: "a", cx: .5, cy: .5, r: .5, extend: ev => ev
19                    .AddStop(offset: 0, stopColor: Color.FromArgb(0xff, 0xff, 0x00))
20                    .AddStop(offset: .75, stopColor: Color.FromArgb(0xff, 0xff, 0x00))
21                    .AddStop(offset: .95, stopColor: Color.FromArgb(0xee, 0xee, 0x00))
22                    .AddStop(offset: 1, stopColor: Color.FromArgb(0xe8, 0xe8, 0x00))
23                )
24            )
25            .AddCircle(r: 20, fill: "url( #a)", stroke: Color.FromArgb(0, 0, 0), extend: c => c.StrokeWidth(.15))
26            .AddCircle(r: 20, fill: "b")
27            .AddG(g => g.Id("c")
28                .AddEllipse(cx: -6, cy: -7, rx: 2.5, ry: 4)
29                .AddPath(fill: Paint.None, stroke: Color.FromArgb(0, 0, 0), d: "M10.6 2.7a4 4 0 0 0 4 3", extend: e => e.StrokeWidth(.5).StrokeLineCap(StrokeLineCap.Round))
30            )
31            .AddUse(href: "#c", extend: e => e.Transform(t => t.Scale(-1, 1)))
32            .AddPath(d: "M-12 5a13.5 13.5 0 0 0 24 0 13 13 0 0 1-24 0", fill:Paint.None, stroke: Color.FromArgb(0,0,0), extend: e => e.StrokeWidth(.75))
33            .Build(document.FirstChild as SVGSVGElement);
34
35        // Save the SVG document
36        document.Save(OutputFolder + "face.svg");
37    }

This code snippet creates an SVG document with a complex design, demonstrating the flexibility and power of the SVG Builder API for generating custom SVG graphics programmatically. In the C# code above, we create an SVG document with elements such as circles, ellipses, paths, and gradients. The generated SVG image represents a face with a smile (smiley face):

Text “Smiley - a face with a smile - rendering of the face.svg file”

Load SVG from a File

To load SVG from a file bezier-curves.svg, use the default constructor of the SVGDocument class and pass the file path as the input parameter to it.

 1using Aspose.Svg;
 2using System.IO;
 3...
 4    
 5    // Prepare a path to a file loading
 6    string documentPath = Path.Combine(DataDir, "bezier-curves.svg"); 
 7	
 8	// Load an SVG document from the file
 9	using (var document = new SVGDocument(documentPath))
10	{
11	    // Work with the document 
12	}

Load SVG from the Web

The following examples could help you to create a document from URL referring to the XML file:

1using Aspose.Svg;
2...
3
4    // Load SVG from the Web at its URL
5    var documentUrl = new Url("https://docs.aspose.com/svg/files/owl.svg");
6    using (var document = new SVGDocument(documentUrl))
7    {
8        // Work with the SVG document here...
9    }
1using Aspose.Svg;
2...
3
4    // Load SVG from the Web at its URL
5    using (var document = new SVGDocument(new Url("https://docs.aspose.com/svg/files/basic-shapes.svg")))
6    {
7        // Work with the SVG document here...
8    }

If you set a wrong URL that can’t be reached right at this moment, the library throws the DOMException with specialized code ‘NetworkError’ to inform you that the selected resource can not be found.

Read SVG with Resources Async

If SVG contains external resources, it may take time to load all resources completely and, hence, resulting in blocking of the main application thread. In an Async model, the Load and ReadyStateChange events can be subscribed to notify the loading application for complete loading of the SVG file as shown in the following code sample. The Navigate(Url) method of the SVGDocument class is used for the document loading at the specified URL into the current instance.

 1using Aspose.Svg;
 2using System.Threading;
 3...
 4
 5    var documentUrl = new Url("https://docs.aspose.com/svg/files/owl.svg");
 6	var document = new SVGDocument();
 7	var documentEvent = new ManualResetEvent(false);
 8
 9	// Subscribe to the event 'OnReadyStateChange' that will be fired once the document is completely loaded
10	document.OnReadyStateChange += (sender, ev) =>
11	{
12	    if (document.ReadyState == "complete")
13	    {
14	        // Sets the state of the event to signaled to unblock the main thread
15	        documentEvent.Set();
16	    }
17	};
18	// Load the SVG document Async
19	document.Navigate(documentUrl);
20
21	// Blocks the current thread while the document is loading
22	documentEvent.WaitOne();
23
24	// Work with the document

You can download the complete examples and data files from GitHub. You find out about downloading from GitHub and running examples from the How to Run the Examples section.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.