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 ResourceHandler class 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 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 ResourceHandler class is developed for saving SVG content and resources to streams. This class is responsible for handling resources and provides methods that allow you to control what is done with each resource.
Let’s consider an example of saving SVG with resourses to user-specified local file storage. The source
with-resources.svg document and its linked image file are in the same directory. The
FileSystemResourceHandler(customOutDir
) constructor takes a path indicating where the document with resources will be saved and creates a FileSystemResourceHandler
object. The
Save(resourceHandler
) 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-resources.svg");
7
8 // Prepare a full path to an output directory
9 string customOutDir = Path.Combine(Directory.GetCurrentDirectory(), "./../../../../tests-out/save/");
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 FileSystemResourceHandler(customOutDir));
16 }
Save SVG to a Zip Archive
You can implement the
ResourceHandler by creating ZipResourceHandler class. It allows you to create a structured and compressed archive containing SVG documents and associated resources, making it suitable for scenarios such as archiving and storage optimization. The
HandleResource() method in the ZipResourceHandler
class serves to customize the behavior of how individual resources are processed and stored in a Zip archive.
In the following example, the ZipResourceHandler
class is used to save the
with-resources.svg document along with its linked resources to a Zip archive:
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-resources.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/save/archive.zip");
13
14 // Load an SVG document
15 using (var doc = new SVGDocument(inputPath))
16 {
17 // Initialize an instance of the ZipResourceHandler class
18 using (var resourceHandler = new ZipResourceHandler(customArchivePath))
19 {
20 // Save SVG with resources to a Zip archive
21 doc.Save(resourceHandler);
22 }
23 }
The ResourceHandler
class is intended for customer implementation. The ZipResourceHandler
class extends the ResourceHandler
base class and provides a convenient way to manage the entire process of handling and storing resources linked with an SVG document into a Zip archive within the context of the Aspose.SVG for .NET library:
1 internal class ZipResourceHandler : ResourceHandler, IDisposable
2 {
3 private FileStream zipStream;
4 private ZipArchive archive;
5 private int streamsCounter;
6 private bool initialized;
7
8 public ZipResourceHandler(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 override void HandleResource(Resource resource, ResourceHandlingContext context)
17 {
18 var zipUri = (streamsCounter++ == 0
19 ? Path.GetFileName(resource.OriginalUrl.Href)
20 : Path.Combine(Path.GetFileName(Path.GetDirectoryName(resource.OriginalUrl.Href)),
21 Path.GetFileName(resource.OriginalUrl.Href)));
22 var samplePrefix = String.Empty;
23 if (initialized)
24 samplePrefix = "my_";
25 else
26 initialized = true;
27
28 using (var newStream = archive.CreateEntry(samplePrefix + zipUri).Open())
29 {
30 resource.WithOutputUrl(new Url("file:///" + samplePrefix + zipUri)).Save(newStream, context);
31 }
32 }
33
34 private void DisposeArchive()
35 {
36 if (archive != null)
37 {
38 archive.Dispose();
39 archive = null;
40 }
41
42 if (zipStream != null)
43 {
44 zipStream.Dispose();
45 zipStream = null;
46 }
47
48 streamsCounter = 0;
49 }
50
51 public void Dispose()
52 {
53 DisposeArchive();
54 }
55 }
Save SVG to Memory Streams
The
ResourceHandler class implementation in the MemoryResourceHandler class allows saving SVG to memory streams. The following code shows how to use the MemoryResourceHandler
class to store an SVG document in memory, collecting and printing information about the handled resources.
- Initialize an SVG Document using the specified SVG file path.
- Create an instance of the
MemoryResourceHandler
class. This class is designed to capture and store resources within memory streams during the resource-handling process. - Call the
Save()
method of the SVG document and pass it theMemoryResourceHandler
instance as an argument. This associates the resource handling logic of theMemoryResourceHandler
with the SVG document-saving process. - Use the
PrintInfo()
method of theMemoryResourceHandler
to print information about the handled resources.
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-resources.svg");
8
9 // Initialize an SVG document
10 using (var doc = new SVGDocument(inputPath))
11 {
12 // Create an instance of the MemoryResourceHandler class and save SVG to memory
13 var resourceHandler = new MemoryResourceHandler();
14 doc.Save(resourceHandler);
15 resourceHandler.PrintInfo();
16 }
After the example run, the message about memory storage will be printed:
uri:memory:///with-resources.svg, length:556
uri:memory:///photo.png, length:57438
The
ResourceHandler is a base class that supports the creation and management of output streams. The MemoryResourceHandler
class allows you to capture and store resources in-memory streams, providing a dynamic and flexible way to handle resources without physically saving them to the file system. The following code snippet shows the realization of the ResourceHandler
in the MemoryResourceHandler class:
1 internal class MemoryResourceHandler : ResourceHandler
2 {
3 public List<Tuple<Stream, Resource>> Streams;
4
5 public MemoryResourceHandler()
6 {
7 Streams = new List<Tuple<Stream, Resource>>();
8 }
9
10 public override void HandleResource(Resource resource, ResourceHandlingContext context)
11 {
12 var outputStream = new MemoryStream();
13 Streams.Add(Tuple.Create<Stream, Resource>(outputStream, resource));
14 resource
15 .WithOutputUrl(new Url(Path.GetFileName(resource.OriginalUrl.Pathname), "memory:///"))
16 .Save(outputStream, context);
17 }
18
19 public void PrintInfo()
20 {
21 foreach (var stream in Streams)
22 Console.WriteLine($"uri:{stream.Item2.OutputUrl}, length:{stream.Item1.Length}");
23 }
24 }
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.