Save an SVG Document - C#

Save an SVG document

Most of the tasks, you need to perform, require saving a document. Once you load the existing file or create an SVG document from scratch, you can save your changes using one of SVGDocument.Save() methods. There are overloaded methods that allow saving SVG to a file, stream, Zip archive or Url.

In this article, we review the SVG documents saving to the same format. You find out how to save your SVG file using Save() methods of the SVGDocument class. Moreover, Aspose.SVG for .NET provides the IOutputStorage interface that allows save SVG documents with resources to streams and manage them.

The scenarios of converting and rendering SVG to other formats are viewed in the How to Convert SVG Files section.

Save SVG to a File

The following code snippet demonstrates the use of the SVGDocument.Save() method to save an SVG document to a file:

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

Save SVG to a Url

It is necessary to specify a full Url path for the document lineto.svg saving and pass the url object to the Save() method that saves the document to a local file specified by Url. The following code example shows how to save a document to a Url:

 1using System.IO;
 2using Aspose.Svg;
 3...
 4
 5    // Set a full path for an SVG document saving
 6	var url = new Url(Path.Combine(OutputDir, "lineto_out.svg"), Directory.GetCurrentDirectory());
 7
 8    //  Load the SVG document from a file
 9    using (var document = new SVGDocument(Path.Combine(DataDir, "lineto.svg")))
10    {
11        // Work with the document
12        
13        // Save SVG to Url
14        document.Save(url);
15    }

Save SVG to a Local File System Storage

The SVG document can contain different resources like CSS, external images and files. Aspose.SVG provides a way to save SVG with all linked files - the IOutputStorage interface is developed for saving SVG content and resources to streams.

Let’s consider an example of saving SVG with linked file to user-specified local file storage. The source with-external-html.svg document with the joined simple-html.htm file are in the same directory. The LocalFileSystemStorage(customOutDir) constructor creates an object that is a file system storage. The Save(IOutputStorage) method takes this object and saves SVG to the output storage.

 1using System.IO;
 2using Aspose.Svg.IO;
 3...
 4
 5	// Prepare a path to a source SVG file  
 6    string inputPath = Path.Combine(DataDir, "with-external-html.svg");
 7
 8    // Prepare a full path to an output directory 
 9    string customOutDir = Path.Combine(Directory.GetCurrentDirectory(), "./../../../../tests-out/saving");
10
11    // Load the SVG document from a file
12    using (var doc = new SVGDocument(inputPath))
13    {
14        // Save SVG with resources
15        doc.Save(new LocalFileSystemStorage(customOutDir));
16    }

Save SVG to a Zip Archive

The IOutputStorage interface is a base interface that supports the creation and management of output streams. It contains two methods to manage streams: CreateStream() and ReleaseStream(). The OutputStream Class is a surrogate stream that wraps the real output stream and controls access to it. OutputStream contains URI data that describes the location of the output stream.

You can implement the IOutputStorage interface by creating ZipStorage class. View the example of saving SVG with resources (two files from the previous example) to a ZIP archive using ZipStorage class.

 1using System.IO;
 2using Aspose.Svg.IO;
 3using System.IO.Compression;
 4...
 5
 6	// Prepare a path to a source SVG file 
 7    string inputPath = Path.Combine(DataDir, "with-external-html.svg");
 8    
 9    var dir = Directory.GetCurrentDirectory();
10
11    // Prepare a full path to an output zip storage
12    string customArchivePath = Path.Combine(dir, "./../../../../tests-out/saving/archive.zip");
13
14    // Load the SVG document 
15    using (var doc = new SVGDocument(inputPath))
16    {
17        // Initialize an instance of the ZipStorage class
18        using (var zipSrorage = new ZipStorage(customArchivePath))
19        {
20            // Save SVG with resources to a Zip archive
21            doc.Save(zipSrorage);
22        }
23    }

The IOutputStorage interface is intended for customers implementation. The following code snippet shows the realization of the IOutputStorage in the ZipStorage class to demonstrate saving an SVG document to a Zip archive.

 1internal class ZipStorage : IOutputStorage, IDisposable
 2{
 3    private FileStream zipStream;
 4    private ZipArchive archive;
 5    private int streamsCounter;
 6    private bool initialized;
 7
 8    public ZipStorage(string name)
 9    {
10        DisposeArchive();
11        zipStream = new FileStream(name, FileMode.Create);
12        archive = new ZipArchive(zipStream, ZipArchiveMode.Update);
13        initialized = false;
14    }
15
16    public OutputStream CreateStream(OutputStreamContext context)
17    {
18        var zipUri = (streamsCounter++ == 0 ? Path.GetFileName(context.Uri) :
19            Path.Combine(Path.GetFileName(Path.GetDirectoryName(context.Uri)), Path.GetFileName(context.Uri)));
20        var samplePrefix = String.Empty;
21        if (initialized)
22            samplePrefix = "my_";
23        else
24            initialized = true;
25
26        var newStream = archive.CreateEntry(samplePrefix + zipUri).Open();
27        var outputStream = new OutputStream(newStream, "file:///" + samplePrefix + zipUri);
28        return outputStream;
29    }
30
31    public void ReleaseStream(OutputStream stream)
32    {
33        stream.Flush();
34        stream.Close();
35    }
36
37    private void DisposeArchive()
38    {
39        if (archive != null)
40        {
41            archive.Dispose();
42            archive = null;
43        }
44        if (zipStream != null)
45        {
46            zipStream.Dispose();
47            zipStream = null;
48        }
49        streamsCounter = 0;
50    }
51
52    public void Dispose()
53    {
54        DisposeArchive();
55    }
56}

Save SVG to Memory Streams

The IOutputStorage interface implementation allows saving SVG to memory streams:

 1using System.IO;
 2using Aspose.Svg.IO;
 3using System.Collections.Generic;
 4...
 5
 6    // Prepare a path to a source SVG file
 7    string inputPath = Path.Combine(DataDir, "with-external-html.svg");
 8
 9    using (var doc = new SVGDocument(inputPath))
10    {
11        // Create an instance of the MemoryOutputStorage class and save SVG to memory
12        var memoryStorage = new MemoryOutputStorage();
13        doc.Save(memoryStorage);
14	    memoryStorage.PrintInfo();
15    }

After the example run, the message about memory storage will be printed:

uri:memory:///with-external-html.svg, length:570
uri:memory:///simple-html.htm, length:369

The following code snippet shows the realization of the IOutputStorage in the MemoryOutputStorage class to demonstrate saving an SVG document to memory streams.

 1internal class MemoryOutputStorage : IOutputStorage
 2{
 3    public List<Tuple<OutputStream, string>> Streams;
 4
 5    public MemoryOutputStorage()
 6    {
 7        Streams = new List<Tuple<OutputStream, string>>();
 8    }
 9
10    public OutputStream CreateStream(OutputStreamContext context)
11    {
12        var normalizedPath = new Url(context.Uri).Pathname;
13        var uri = new Url(Path.GetFileName(normalizedPath), "memory:///").Href;
14        var outputStream = new OutputStream(new MemoryStream(), uri);
15        Streams.Add(Tuple.Create(outputStream, uri));
16        return outputStream;
17    }
18
19    public void ReleaseStream(OutputStream stream)
20    {
21        stream.Flush();
22    }
23
24    public void PrintInfo()
25    {
26        foreach (var stream in Streams)
27            Console.WriteLine($"uri:{stream.Item2}, length:{stream.Item1.Length}");
28    }
29}

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

You can try to convert SVG documents to various other formats with our Free Online SVG Converter.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.