Create, Load and Read SVG Files in C#

This guide shows how to create, load, and read SVG files in C# with Aspose.SVG for .NET. You will learn how to initialize an SVGDocument from an empty document, string content, stream, local file, URL, and how to load SVG documents with external resources asynchronously.

The SVGDocument class is the entry point for working with SVG content in Aspose.SVG for .NET. It represents the root of the SVG DOM hierarchy, holds the entire document content, and follows the W3C SVG 2.0 and WHATWG DOM specifications.

SVG files can be created and loaded:

The following C# examples demonstrate the most common SVGDocument constructors and loading scenarios.

Quick Start: Create an SVG Document in C#

The quickest way to create an SVG document is to pass SVG markup as a string to the SVGDocument constructor. This is useful when SVG content is generated dynamically in your application:

1using Aspose.Svg;
2...
3
4    string svgContent = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"100\" height=\"100\"><circle cx=\"50\" cy=\"50\" r=\"40\" /></svg>";
5
6    using (SVGDocument document = new SVGDocument(svgContent, "."))
7    {
8        document.Save("circle.svg");
9    }

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 (SVGDocument document = new SVGDocument())
6    {
7        // Work with the SVG document here...
8    }

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

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

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

Use the SVGDocument(string, string) constructor when SVG markup already exists in memory, for example after being generated by your application or received from a database, API, or user input.

The second constructor argument is the base URI. Aspose.SVG uses it to resolve relative paths inside the SVG, such as linked images, CSS files, or fonts. If the SVG markup does not reference external resources, you can pass ".", as shown in the quick start example above. If it does, pass the folder or URL where those resources are located:

 1using Aspose.Svg;
 2using System.IO;
 3...
 4
 5    // SVG markup contains a relative reference to an external image
 6    string documentContent = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"120\"><image href=\"images/logo.png\" width=\"200\" height=\"120\" /></svg>";
 7
 8    // Relative paths in the SVG are resolved against this base URI
 9    string baseUri = Path.Combine(DataDir, "assets") + Path.DirectorySeparatorChar;
10
11	// Initialize an SVG document from a string content
12	using (SVGDocument document = new SVGDocument(documentContent, baseUri))
13	{
14	    // Work with the document here...
15	}

Load SVG from a Stream

To load SVG from a stream, use one of the SVGDocument() constructors that accepts a Stream object. This pattern is useful for reading SVG from uploaded files, embedded resources, memory buffers, or other non-file sources:

 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 (FileStream stream = new FileStream(documentPath, FileMode.Open, FileAccess.Read))
10	{
11	    // Initialize an SVG document from the stream
12		using (SVGDocument 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 create complex SVG graphics with detailed customization options. For more information, see 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 System.IO;
2using Aspose.Svg;
3using Aspose.Svg.Builder;
4using System.Drawing;
 1// Create SVG using Builder API
 2
 3// Initialize an SVG document
 4using (SVGDocument document = new SVGDocument())
 5{
 6    // Create an <svg> element with specified width, height and viewBox, and add into it other required elements
 7    SVGSVGElement svg = new SVGSVGElementBuilder()
 8        .Width(100).Height(100)
 9        .ViewBox(-21, -21, 42, 42)
10        .AddDefs(def => def
11            .AddRadialGradient(id: "b", cx: .2, cy: .2, r: .5, fx: .2, fy: .2, extend: ev => ev
12                .AddStop(offset: 0, stopColor: Color.FromArgb(0xff, 0xff, 0xFF), stopOpacity: .7)
13                .AddStop(offset: 1, stopColor: Color.FromArgb(0xff, 0xff, 0xFF), stopOpacity: 0)
14            )
15            .AddRadialGradient(id: "a", cx: .5, cy: .5, r: .5, extend: ev => ev
16                .AddStop(offset: 0, stopColor: Color.FromArgb(0xff, 0xff, 0x00))
17                .AddStop(offset: .75, stopColor: Color.FromArgb(0xff, 0xff, 0x00))
18                .AddStop(offset: .95, stopColor: Color.FromArgb(0xee, 0xee, 0x00))
19                .AddStop(offset: 1, stopColor: Color.FromArgb(0xe8, 0xe8, 0x00))
20            )
21        )
22        .AddCircle(r: 20, fill: "url(#a)", stroke: Color.FromArgb(0, 0, 0), extend: c => c.StrokeWidth(.15))
23        .AddCircle(r: 20, fill: "b")
24        .AddG(g => g.Id("c")
25            .AddEllipse(cx: -6, cy: -7, rx: 2.5, ry: 4)
26            .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))
27        )
28        .AddUse(href: "#c", extend: e => e.Transform(t => t.Scale(-1, 1)))
29        .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))
30        .Build(document.FirstChild as SVGSVGElement);
31
32    // Save the SVG document
33    document.Save(Path.Combine(OutputDir, "face.svg"));
34}

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):

Smiley – a face with a smile – rendering of the face.svg file

Load SVG from a Local 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 (SVGDocument document = new SVGDocument(documentPath))
10	{
11	    // Work with the document 
12	}

Load SVG from the Web

You can also load SVG directly from a URL. The following examples show how to create an SVGDocument from a web address that points to an SVG file:

1using Aspose.Svg;
2...
3
4    // Load SVG from the Web at its URL
5    Url documentUrl = new Url("https://docs.aspose.com/svg/files/owl.svg");
6    using (SVGDocument 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 (SVGDocument 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 cannot be reached, the library throws a DOMException with the specialized code NetworkError to inform you that the selected resource cannot be found.

Load SVG with External Resources Asynchronously

If an SVG document references external resources such as images, fonts, CSS files, or scripts, loading may take additional time and can block the main application thread. In an asynchronous loading model, you can subscribe to the Load and ReadyStateChange events and notify your application when the SVG document and its resources are ready.

The Navigate(Url) method of the SVGDocument class loads the document from the specified URL into the current instance.

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

FAQ

1. Why are images, fonts, or CSS files not loaded when I create SVG from a string or stream?
When SVG is created from a string or stream, relative resource paths are resolved against the base URI passed to the SVGDocument constructor. If linked images, fonts, or CSS files are not loaded, check that the base URI points to the folder or URL where those resources are located.

2. What happens if an SVG file contains invalid markup?
Aspose.SVG parses SVG as XML-based content. If the markup is malformed or required resources cannot be resolved, document loading or later processing may fail. Validate generated SVG markup and handle loading exceptions in production code.

3. Can I modify an SVGDocument after loading it?
Yes. After an SVG file is loaded, you can navigate and modify its DOM, add or remove elements, update attributes, apply styles, and save the result. For detailed editing examples, see the Edit SVG File article.

4. Is SVGDocument suitable for server-side applications?
Yes. Aspose.SVG for .NET can be used in backend services, ASP.NET applications, batch processors, and document automation workflows without relying on browser automation.

5. What is the difference between SVG Builder API and DOM manipulation?
SVG Builder API is convenient for creating new SVG structures in C# step by step. DOM manipulation is better when you work with an already loaded SVG document and need to change its existing elements, attributes, or styles.

Next Steps