Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Большинство задач, которые вам необходимо выполнить, требуют сохранения документа. Загрузив существующий файл или создав документ SVG с нуля, вы можете сохранить изменения, используя один из методов SVGDocument.Save(). Существуют перегруженные методы, позволяющие сохранять SVG в файл, поток, Zip-архив или URL-адрес.
В этой статье мы рассмотрим сохранение документов SVG в том же формате. Вы узнаете, как сохранить файл SVG, используя методы Save() класса SVGDocument. Более того, Aspose.SVG для .NET предоставляет класс ResourceHandler, который позволяет сохранять документы SVG с ресурсами в потоки и управлять ими.
Сценарии конвертации и рендеринга SVG в другие форматы рассматриваются в разделе Как конвертировать файлы SVG.
Следующий фрагмент кода демонстрирует использование метода SVGDocument.Save() для сохранения документа SVG в файл:
1using Aspose.Svg;
2using System.IO; 1// Save SVG to file using C#
2
3// Prepare a path to save an SVG document
4string documentPath = Path.Combine(OutputDir, "circles_out.svg");
5
6// Load the SVG document from a file
7using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "circles.svg")))
8{
9 // Work with the document
10
11 // Save SVG to a file
12 document.Save(documentPath);
13}Необходимо указать полный URL-путь для сохранения документа
lineto.svg и передать объект url методу Save(), который сохраняет документ в файл, указанный URL-адресом. В следующем примере кода показано, как сохранить документ по URL-адресу:
1using Aspose.Svg;
2using System.IO; 1// Save SVG to Url using C#
2
3// Set a full path for an SVG document saving
4Url url = new Url(Path.Combine(OutputUrl, "lineto_out.svg"), Directory.GetCurrentDirectory());
5
6// Load the SVG document from a file
7using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "lineto.svg")))
8{
9 // Work with the document
10
11 // Save the document to a Url
12 document.Save(url);
13}Документ SVG может содержать различные ресурсы, такие как CSS, внешние изображения и файлы. Aspose.SVG предоставляет способ сохранения SVG со всеми связанными файлами – класс ResourceHandler разработан для сохранения содержимого и ресурсов SVG в потоки. Этот класс отвечает за обработку ресурсов и предоставляет методы, позволяющие контролировать действия с каждым ресурсом.
Давайте рассмотрим пример сохранения SVG с ресурсами в указанном пользователем локальном файловом хранилище. Исходный документ
with-resources.svg и связанный с ним файл изображения находятся в одном каталоге. Конструктор
FileSystemResourceHandler(customOutDir) принимает путь, указывающий, где будет сохранен документ с ресурсами, и создает объект FileSystemResourceHandler. Метод
Save(resourceHandler) принимает этот объект и сохраняет SVG в выходное хранилище.
1using System.IO;
2using Aspose.Svg.IO; 1// Save an SVG document along with its external resources in C#
2
3// Prepare a path to a source SVG file
4string inputPath = Path.Combine(DataDir, "with-resources.svg");
5
6// Prepare a full path to an output directory
7string customOutDir = Path.Combine(Directory.GetCurrentDirectory(), "./../../../../tests-out/saving/");
8
9// Load an SVG document from a file
10using (SVGDocument doc = new SVGDocument(inputPath))
11{
12 // Save SVG with resources
13 doc.Save(new FileSystemResourceHandler(customOutDir));
14}Вы можете реализовать
ResourceHandler, создав класс ZipResourceHandler. Он позволяет создавать структурированный и сжатый архив, содержащий документы SVG и связанные ресурсы, что делает его пригодным для таких сценариев, как архивирование и оптимизация хранения. Метод
HandleResource() в классе ZipResourceHandler служит для настройки поведения обработки и хранения отдельных ресурсов в Zip-архиве.
В следующем примере класс ZipResourceHandler используется для сохранения документа
with-resources.svg вместе со связанными с ним ресурсами в Zip-архив:
1using System.IO;
2using Aspose.Svg.IO;
3using System.IO.Compression; 1// Save SVG to a Zip Archive using C#
2
3// Prepare a path to a source SVG file
4string inputPath = Path.Combine(DataDir, "with-resources.svg");
5
6string dir = Directory.GetCurrentDirectory();
7
8// Prepare a full path to an output Zip storage
9string customArchivePath = Path.Combine(dir, "./../../../../tests-out/saving/archive.zip");
10
11// Load an SVG document
12using (SVGDocument doc = new SVGDocument(inputPath))
13{
14 // Initialize an instance of the ZipResourceHandler class
15 using (ZipResourceHandler resourceHandler = new ZipResourceHandler(customArchivePath))
16 {
17 // Save SVG with resources to a Zip archive
18 doc.Save(resourceHandler);
19 }
20}Класс ResourceHandler предназначен для реализации пользователями. Класс ZipResourceHandler расширяет базовый класс ResourceHandler и предоставляет удобный способ управления всем процессом обработки и сохранения ресурсов, связанных с документом SVG, в Zip-архив в контексте библиотеки Aspose.SVG for .NET:
1// Custom resource handler to save SVG with resources into a ZIP archive
2
3internal class ZipResourceHandler : ResourceHandler, IDisposable
4{
5 private FileStream zipStream;
6 private ZipArchive archive;
7 private int streamsCounter;
8 private bool initialized;
9
10 public ZipResourceHandler(string name)
11 {
12 DisposeArchive();
13 zipStream = new FileStream(name, FileMode.Create);
14 archive = new ZipArchive(zipStream, ZipArchiveMode.Update);
15 initialized = false;
16 }
17
18 public override void HandleResource(Resource resource, ResourceHandlingContext context)
19 {
20 string zipUri = (streamsCounter++ == 0
21 ? Path.GetFileName(resource.OriginalUrl.Href)
22 : Path.Combine(Path.GetFileName(Path.GetDirectoryName(resource.OriginalUrl.Href)),
23 Path.GetFileName(resource.OriginalUrl.Href)));
24 string samplePrefix = String.Empty;
25 if (initialized)
26 samplePrefix = "my_";
27 else
28 initialized = true;
29
30 using (Stream newStream = archive.CreateEntry(samplePrefix + zipUri).Open())
31 {
32 resource.WithOutputUrl(new Url("file:///" + samplePrefix + zipUri)).Save(newStream, context);
33 }
34 }
35
36 private void DisposeArchive()
37 {
38 if (archive != null)
39 {
40 archive.Dispose();
41 archive = null;
42 }
43
44 if (zipStream != null)
45 {
46 zipStream.Dispose();
47 zipStream = null;
48 }
49
50 streamsCounter = 0;
51 }
52
53 public void Dispose()
54 {
55 DisposeArchive();
56 }
57}Реализация класса
ResourceHandler в классе MemoryResourceHandler позволяет сохранять SVG в потоках памяти. В следующем примере показано, как использовать класс MemoryResourceHandler для хранения документа SVG в памяти, сбора и печати информации об обрабатываемых ресурсах.
MemoryResourceHandler. Этот класс предназначен для захвата и хранения ресурсов в потоках памяти во время процесса обработки ресурсов.Save() документа SVG и передайте ему экземпляр MemoryResourceHandler в качестве аргумента. Это связывает логику обработки ресурсов MemoryResourceHandler с процессом сохранения документа SVG.PrintInfo() класса MemoryResourceHandler для печати информации об обрабатываемых ресурсах.1using System.IO;
2using Aspose.Svg.IO;
3using System.Collections.Generic; 1// Save an SVG document to memory with a resource handler in C#
2
3// Prepare a path to a source SVG file
4string inputPath = Path.Combine(DataDir, "with-resources.svg");
5
6// Initialize an SVG document
7using (SVGDocument doc = new SVGDocument(inputPath))
8{
9 // Create an instance of the MemoryResourceHandler class and save SVG to memory
10 MemoryResourceHandler resourceHandler = new MemoryResourceHandler();
11 doc.Save(resourceHandler);
12 resourceHandler.PrintInfo();
13}После запуска примера будет напечатано сообщение о хранении в памяти:
uri:memory:///with-resources.svg, length:556uri:memory:///photo.png, length:57438
ResourceHandler – это базовый класс, который поддерживает создание потоков вывода и управление ими. Класс MemoryResourceHandler позволяет захватывать и хранить потоки ресурсов в памяти, обеспечивая динамический и гибкий способ обработки ресурсов без физического сохранения их в файловой системе. В следующем фрагменте кода показана реализация
ResourceHandler в классе MemoryResourceHandler:
1// Handle and save SVG resources to memory streams in C#
2
3internal class MemoryResourceHandler : ResourceHandler
4{
5 public List<Tuple<Stream, Resource>> Streams;
6
7 public MemoryResourceHandler()
8 {
9 Streams = new List<Tuple<Stream, Resource>>();
10 }
11
12 public override void HandleResource(Resource resource, ResourceHandlingContext context)
13 {
14 MemoryStream outputStream = new MemoryStream();
15 Streams.Add(Tuple.Create<Stream, Resource>(outputStream, resource));
16 resource
17 .WithOutputUrl(new Url(Path.GetFileName(resource.OriginalUrl.Pathname), "memory:///"))
18 .Save(outputStream, context);
19 }
20
21 public void PrintInfo()
22 {
23 foreach (Tuple<Stream, Resource> stream in Streams)
24 Console.WriteLine($"uri:{stream.Item2.OutputUrl}, length:{stream.Item1.Length}");
25 }
26}Вы можете загрузить полные примеры и файлы данных с GitHub. О загрузке с GitHub и запуске примеров вы узнаете из раздела Как запускать примеры.
Вы можете попробовать конвертировать документы SVG в другие форматы с помощью нашего Бесплатного онлайн-конвертера SVG.
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.