Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aspose-com-gists/29c524bb68b049b571ce14a6146c2bd1 to your computer and use it in GitHub Desktop.

Select an option

Save aspose-com-gists/29c524bb68b049b571ce14a6146c2bd1 to your computer and use it in GitHub Desktop.
This Gist contains C# examples Aspose.SVG for .NET – Basic Operations

Aspose.SVG for .NET – Create, Load, Edit, Save, and Navigate SVG in C#

This gist collection contains C# code examples from the SVG Basic Operations chapter of the Aspose.SVG for .NET documentation. Learn how to create, load, edit, navigate, inspect, and save SVG documents programmatically, including SVGZ compression and external resource handling.

What's Included?

This gist collection provides ready-to-use C# examples covering:

  • Creating SVG documents – Create empty SVG documents, generate SVG from string content, and use the SVG Builder API.
  • Loading SVG files – Load SVG documents from files, streams, URLs, and strings with external resource resolution.
  • Editing SVG documents – Add shapes, edit path data, and modify existing SVG content using the DOM API.
  • Navigating and inspecting SVG – Traverse SVG elements and inspect document content programmatically.
  • Using CSS Selectors and XPath – Find and modify SVG elements with CSS selectors and XPath expressions.
  • Saving SVG documents – Save SVG files and external resources to files, memory streams, ZIP archives, or URLs.
  • Converting SVG and SVGZ files – Save SVG as compressed SVGZ and convert SVGZ files back to SVG.

Getting Started

The C# code snippets are self-contained and intended to provide a quick start when learning and integrating Aspose.SVG for .NET into your own projects.

  1. Make sure you have the Aspose.SVG for .NET library installed.
  2. Clone or download this gist repository.
  3. Open any example in your preferred .NET environment.
  4. Adjust file paths, input, and output parameters as needed.
  5. Run the code to see how specific features work in practice.

You can download a free trial of Aspose.SVG for .NET and use a temporary license for unrestricted access.

Prerequisites

  • .NET Platforms: .NET Framework 4.6.1+, .NET Core 2.0+, or .NET 5+.
  • Supported OS: Windows, Linux, macOS.
  • Development environment such as Visual Studio or JetBrains Rider.
  • Aspose.SVG for .NET installed via NuGet.

Resources

Contributing

If you have questions or suggestions for improvement on these examples, please visit the Aspose.SVG Support Forum. We welcome your comments and feedback.

Aspose.SVG for .NET – Basic Operations
// Add a circle element to an existing SVG document in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-file/
// Set the SVG namespace URI
string SvgNamespace = "http://www.w3.org/2000/svg";
// Load an SVG document from a file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "basic-shapes.svg")))
{
// Get the root <svg> element of the document
SVGSVGElement svgElement = document.RootElement;
// Create a <circle> element
SVGCircleElement circleElement = (SVGCircleElement)document.CreateElementNS(SvgNamespace, "circle");
circleElement.Cx.BaseVal.Value = 100F;
circleElement.Cy.BaseVal.Value = 100F;
circleElement.R.BaseVal.Value = 50F;
circleElement.SetAttribute("fill", "Salmon");
// Add the <circle> element as the first child to <svg> element
svgElement.InsertBefore(circleElement, svgElement.FirstChild);
// Work with the document here...
// Add a polyline and change stroke attributes for all circle and ellipse elements (see later)
// Save the document
document.Save(Path.Combine(OutputDir, "basic-shapes_add-circle.svg"));
}
// Add a polyline and update existing SVG shapes in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-file/
string inputPath = Path.Combine(DataDir, "shapes.svg");
string outputPath = Path.Combine(OutputDir, "updated-shapes.svg");
const string SvgNamespace = "http://www.w3.org/2000/svg";
using (SVGDocument document = new SVGDocument(inputPath))
{
SVGSVGElement svgElement = document.RootElement;
SVGPolylineElement polylineElement = (SVGPolylineElement)document.CreateElementNS(SvgNamespace, "polyline");
SVGPoint point1 = svgElement.CreateSVGPoint();
point1.X = 270;
point1.Y = 240;
SVGPoint point2 = svgElement.CreateSVGPoint();
point2.X = 290;
point2.Y = 220;
SVGPoint point3 = svgElement.CreateSVGPoint();
point3.X = 310;
point3.Y = 240;
polylineElement.Points.AppendItem(point1);
polylineElement.Points.AppendItem(point2);
polylineElement.Points.AppendItem(point3);
polylineElement.SetAttribute("stroke", "grey");
polylineElement.SetAttribute("stroke-width", "5");
polylineElement.SetAttribute("fill", "none");
// Add the new polyline to the SVG root element.
svgElement.AppendChild(polylineElement);
// Update strokes of circle and ellipse elements already in the SVG document.
foreach (Element element in svgElement.Children)
{
if (element is SVGCircleElement || element is SVGEllipseElement)
{
element.SetAttribute("stroke-width", "6");
element.SetAttribute("stroke", "#C8102E");
}
}
document.Save(outputPath);
}
// Add a circle shape to an existing SVG file in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-file/
string inputPath = Path.Combine(DataDir, "shapes.svg");
string outputPath = Path.Combine(OutputDir, "shapes-with-circle.svg");
const string SvgNamespace = "http://www.w3.org/2000/svg";
using (SVGDocument document = new SVGDocument(inputPath))
{
// Access the root <svg> element, which is present in an SVG document.
SVGSVGElement svgElement = document.RootElement;
// Create a circle and define its geometry and appearance.
SVGCircleElement circle = (SVGCircleElement)document.CreateElementNS(SvgNamespace, "circle");
circle.Cx.BaseVal.Value = 50;
circle.Cy.BaseVal.Value = 50;
circle.R.BaseVal.Value = 40;
circle.SetAttribute("fill", "#3A86FF");
// Add the circle to the document tree and save the edited SVG file.
svgElement.AppendChild(circle);
document.Save(outputPath);
}
// Convert an SVG file to compressed SVGZ format in C#
// Learn more: https://docs.aspose.com/svg/net/convert-svg-to-svgz/
// Load an SVG document
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg")))
{
// Save the document as SVGZ
document.Save(Path.Combine(OutputDir, "shapes.svgz"), SVGSaveFormat.SVGZ);
}
// Convert a compressed SVGZ file to SVG format in C#
// Learn more: https://docs.aspose.com/svg/net/convert-svgz-to-svg/
// Load an SVG document
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svgz")))
{
// Save the document as SVG
document.Save(Path.Combine(OutputDir, "shapes.svg"), SVGSaveFormat.SVG);
}
// Create an empty SVG document using C#
// Learn more: https://docs.aspose.com/svg/net/create-svg-document/
// Prepare an output path to save a document
string documentPath = Path.Combine(OutputDir, "empty.svg");
// Initialize an empty SVG document
using (SVGDocument document = new SVGDocument())
{
// Work with the SVG document here...
// Save the document to a file
document.Save(documentPath);
}
// Create SVG from a memory string using C#
// Learn more: https://docs.aspose.com/svg/net/create-svg-document/
// Prepare SVG code
string documentContent = "<svg xmlns=\"http://www.w3.org/2000/svg\"><circle cx=\"70\" cy=\"70\" r=\"60\" fill=\"#ff0000\" /> <polygon points=\"160,10 350,140 210,350 50,199\" style=\"fill: orange\" /></svg>";
// Initialize an SVG document from a string content
using (SVGDocument document = new SVGDocument(documentContent, "."))
{
// Work with the document
// Save the document to a file
document.Save(Path.Combine(OutputDir, "from-string.svg"));
}
// Create an SVG document from scratch with shapes and text in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-file/
// Set the SVG namespace URI
string SvgNamespace = "http://www.w3.org/2000/svg";
using (SVGDocument document = new SVGDocument())
{
SVGSVGElement svgElement = document.RootElement;
// Create a text element and set its attributes
SVGTextElement textElement = (SVGTextElement)document.CreateElementNS(SvgNamespace, "text");
textElement.Style.FontSize = "2.0em";
textElement.SetAttribute("x", "270px");
textElement.SetAttribute("fill", "darkred");
textElement.SetAttribute("y", "140px");
textElement.TextContent = "I can add elements to SVG!";
// Create a circle element and set its attributes
SVGCircleElement circleElement = (SVGCircleElement)document.CreateElementNS(SvgNamespace, "circle");
circleElement.Cx.BaseVal.Value = 130;
circleElement.Cy.BaseVal.Value = 130;
circleElement.R.BaseVal.Value = 60;
circleElement.SetAttribute("stroke", "salmon");
circleElement.SetAttribute("stroke-width", "70");
circleElement.SetAttribute("fill", "none");
circleElement.SetAttribute("stroke-dasharray", "2,14");
// Add the circle and text elements to the <svg> element
svgElement.AppendChild(circleElement);
svgElement.AppendChild(textElement);
// Save the document
document.Save(Path.Combine(OutputDir, "svg-from-scratch.svg"));
}
// Create SVG from a string and resolve external resources in C#
// Learn more: https://docs.aspose.com/svg/net/create-svg-document/
// Prepare an output path to save a document
string documentPath = Path.Combine(OutputDir, "from-string-with-base-uri.svg");
// SVG markup contains a relative reference to an external image
string documentContent = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"200\" height=\"120\"><image href=\"flower.png\" width=\"200\" height=\"120\" /></svg>";
// Relative paths in the SVG are resolved against this base URI
string baseUri = DataDir;
// Initialize an SVG document from a string content
using (SVGDocument document = new SVGDocument(documentContent, baseUri))
{
// Work with the document here...
// Save the document to a file
document.Save(documentPath);
}
// Create SVG using Builder API
// Learn more: https://docs.aspose.com/svg/net/create-svg-document/
// Initialize an SVG document
using (SVGDocument document = new SVGDocument())
{
// Create an <svg> element with specified width, height and viewBox, and add into it other required elements
SVGSVGElement svg = new SVGSVGElementBuilder()
.Width(100).Height(100)
.ViewBox(-21, -21, 42, 42)
.AddDefs(def => def
.AddRadialGradient(id: "b", cx: .2, cy: .2, r: .5, fx: .2, fy: .2, extend: ev => ev
.AddStop(offset: 0, stopColor: Color.FromArgb(0xff, 0xff, 0xFF), stopOpacity: .7)
.AddStop(offset: 1, stopColor: Color.FromArgb(0xff, 0xff, 0xFF), stopOpacity: 0)
)
.AddRadialGradient(id: "a", cx: .5, cy: .5, r: .5, extend: ev => ev
.AddStop(offset: 0, stopColor: Color.FromArgb(0xff, 0xff, 0x00))
.AddStop(offset: .75, stopColor: Color.FromArgb(0xff, 0xff, 0x00))
.AddStop(offset: .95, stopColor: Color.FromArgb(0xee, 0xee, 0x00))
.AddStop(offset: 1, stopColor: Color.FromArgb(0xe8, 0xe8, 0x00))
)
)
.AddCircle(r: 20, fill: "url(#a)", stroke: Color.FromArgb(0, 0, 0), extend: c => c.StrokeWidth(.15))
.AddCircle(r: 20, fill: "b")
.AddG(g => g.Id("c")
.AddEllipse(cx: -6, cy: -7, rx: 2.5, ry: 4)
.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))
)
.AddUse(href: "#c", extend: e => e.Transform(t => t.Scale(-1, 1)))
.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))
.Build(document.FirstChild as SVGSVGElement);
// Save the SVG document
document.Save(Path.Combine(OutputDir, "face.svg"));
}
// Edit SVG elements with CSS selectors in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-using-css-selectors/
// Load an SVG document
using (SVGDocument document = new SVGDocument(new Url("https://docs.aspose.com/svg/files/owl.svg")))
{
// Get the root <svg> element of the document
SVGSVGElement svgElement = document.RootElement;
// Find the first element that matches the specified in selector
SVGGElement gElement = svgElement.QuerySelector("g") as SVGGElement;
// Find all <circle> elements in a <g> element
NodeList circleNodes = gElement.QuerySelectorAll("circle");
// Make big blue eyes
foreach (Node circleNode in circleNodes)
{
SVGCircleElement circleElement = circleNode as SVGCircleElement;
circleElement.R.BaseVal.Value *= 1.5F;
circleElement.SetAttribute("stroke", "blue");
}
// Get a path for the owl's wing
SVGPathElement wingPath = gElement.QuerySelector("path:nth-child(2)") as SVGPathElement;
// Apply style attributes to the wing
wingPath.SetAttribute("stroke-width", "16");
wingPath.SetAttribute("stroke-dasharray", "2 8");
document.Save(Path.Combine(OutputDir, "owl-edited1.svg"));
}
// Edit an SVG file and convert it to PNG in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-file/
string inputPath = Path.Combine(DataDir, "diagram.svg");
string editedSvgPath = Path.Combine(OutputDir, "diagram-edited.svg");
string pngPath = Path.Combine(OutputDir, "diagram-edited.png");
using (SVGDocument document = new SVGDocument(inputPath))
{
Element title = document.RootElement.QuerySelector("title");
if (title != null)
{
title.TextContent = "Updated SVG diagram";
}
Element highlight = document.RootElement.QuerySelector("#highlight");
if (highlight != null)
{
highlight.SetAttribute("fill", "#2f80ed");
highlight.SetAttribute("transform", "rotate(12 140 100)");
}
document.Save(editedSvgPath);
ImageSaveOptions options = new ImageSaveOptions();
Converter.ConvertSVG(document, options, pngPath);
}
// Edit SVG path data programmatically in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-file/
// Set the SVG namespace URI
string SvgNamespace = "http://www.w3.org/2000/svg";
using (SVGDocument document = new SVGDocument())
{
SVGSVGElement svgElement = document.RootElement;
// Create a <path> element
SVGPathElement pathElement = (SVGPathElement)document.CreateElementNS(SvgNamespace, "path");
// Set d attribute parameters – SVG path data
pathElement.SetAttribute("d", "M 10 200 Q 25 110 180 200 T 300 250 T 420 250 T 490 150");
// Edit SVG path
foreach (SVGPathSeg pathSeg in pathElement.PathSegList)
{
// Editing T commands parameters
if (pathSeg is SVGPathSegCurvetoQuadraticSmoothAbs)
{
SVGPathSegCurvetoQuadraticSmoothAbs pathSegCurvetoQuadraticSmoothAbs = pathSeg as SVGPathSegCurvetoQuadraticSmoothAbs;
pathSegCurvetoQuadraticSmoothAbs.X -= 60;
pathSegCurvetoQuadraticSmoothAbs.Y -= 65;
}
// Editing M command parameters
if (pathSeg is SVGPathSegMovetoAbs)
{
SVGPathSegMovetoAbs pathSegMovetoAbs = pathSeg as SVGPathSegMovetoAbs;
pathSegMovetoAbs.X = 200;
pathSegMovetoAbs.Y = 100;
}
}
// Set fill and stroke attributes
pathElement.SetAttribute("stroke", "red");
pathElement.SetAttribute("fill", "none");
pathElement.SetAttribute("stroke-width", "4");
// Add the <path> element as the first child to the <svg> element
svgElement.InsertBefore(pathElement, svgElement.FirstChild);
// Save the document
document.Save(Path.Combine(OutputDir, "edit-svg-path-data.svg"));
}
// Select SVG elements with XPath expressions in C#
// Learn more: https://docs.aspose.com/svg/net/navigation-inspection/
// Load an SVG document
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg")))
{
// Evaluate XPath expression
IXPathResult xpathResult = document.Evaluate("//rect[@x='120']", document, null, (Dom.XPath.XPathResultType)XPathResultType.Any, null);
// Get the evaluated node
Console.WriteLine((xpathResult.IterateNext() as Element)?.OuterHTML);
}
// Extract information about a specific SVG element in C#
// Learn more: https://docs.aspose.com/svg/net/navigation-inspection/
string documentPath = Path.Combine(DataDir, "shapes_svg.svg");
// Load a document from a file
using (SVGDocument document = new SVGDocument(documentPath))
{
// Get the root <svg> element of the document
Element svg = document.DocumentElement;
// Find the first child element with a given tag name
SVGGElement g = svg.GetElementsByTagName("g").First() as SVGGElement;
SVGRectElement rect = g.FirstElementChild as SVGRectElement;
Console.WriteLine("Height: {0}", rect.Height); // 100
Console.WriteLine("Width: {0}", rect.Width); // 100
}
// Find SVG elements with CSS selectors in C#
// Learn more: https://docs.aspose.com/svg/net/navigation-inspection/
string inputPath = Path.Combine(DataDir, "shapes.svg");
using (SVGDocument document = new SVGDocument(inputPath))
{
// Select only rectangles whose style attribute contains "FireBrick".
NodeList fireBrickRectangles = document.QuerySelectorAll("rect[style*='FireBrick']");
if (fireBrickRectangles.Length == 0)
{
Console.WriteLine("No rectangles with FireBrick in the style attribute were found.");
return;
}
foreach (Element rectangle in fireBrickRectangles)
{
Console.WriteLine(rectangle.GetAttribute("id"));
}
}
// View SVG document content as OuterHTML in C#
// Learn more: https://docs.aspose.com/svg/net/navigation-inspection/
using (var document = new SVGDocument(Path.Combine(DataDir, "shapes.svg")))
{
var rect = document.GetElementsByTagName("rect").First() as SVGRectElement;
if (rect != null)
{
Console.WriteLine($"Width: {rect.Width.BaseVal.Value}");
Console.WriteLine($"Height: {rect.Height.BaseVal.Value}");
Console.WriteLine($"Style: {rect.GetAttribute("style")}");
}
}
// Iterate SVG rectangle nodes with a custom NodeFilter in C#
// Learn more: https://docs.aspose.com/svg/net/navigation-inspection/
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes.svg")))
{
// Create a node iterator
using (INodeIterator iterator = document.CreateNodeIterator(document, NodeFilter.SHOW_ALL, new RectFilter()))
{
Node node;
while ((node = iterator.NextNode()) != null)
{
}
}
}
// Load SVG from a file using C#
// Learn more: https://docs.aspose.com/svg/net/create-svg-document/
// Prepare a path to a file loading
string documentPath = Path.Combine(DataDir, "bezier-curves.svg");
// Load an SVG document from the file
using (SVGDocument document = new SVGDocument(documentPath))
{
// Work with the document
// Save the document to a file
document.Save(Path.Combine(OutputDir, "from-file.svg"));
}
// Load SVG from a stream with C#
// Learn more: https://docs.aspose.com/svg/net/create-svg-document/
// Prepare a path to a file required for a FileStream object creating
string documentPath = Path.Combine(DataDir, "bezier-curves.svg");
// Create a FileStream object
using (FileStream stream = new FileStream(documentPath, FileMode.Open, FileAccess.Read))
{
// Initialize an SVG document from the stream
using (SVGDocument document = new SVGDocument(stream, "."))
{
// Work with the document
// Save the document
document.Save(Path.Combine(OutputDir, "from-stream.svg"));
}
}
// Load SVG from URL using C#
// Learn more: https://docs.aspose.com/svg/net/create-svg-document/
// Load SVG from the Web by its URL
Url documentUrl = new Url("https://docs.aspose.com/svg/files/owl.svg");
using (SVGDocument document = new SVGDocument(documentUrl))
{
// Work with the document here...
}
// Load SVG asynchronously using C#
// Learn more: https://docs.aspose.com/svg/net/create-svg-document/
Url documentUrl = new Url("https://docs.aspose.com/svg/files/owl.svg");
ManualResetEvent documentEvent = new ManualResetEvent(false);
SVGDocument document = new SVGDocument();
// Subscribe to the event 'OnReadyStateChange' that will be fired once the document is completely loaded
document.OnReadyStateChange += (sender, ev) =>
{
if (document.ReadyState == "complete")
{
// Sets the state of the event to signaled to unblock the main thread
documentEvent.Set();
}
};
// Load an SVG document Async
document.Navigate(documentUrl);
// Blocks the current thread while the document is loading
documentEvent.WaitOne();
// Work with the document
// Implement a resource handler to save SVG resources in memory in C#
// Learn more: https://docs.aspose.com/svg/net/save-svg-document/
internal class MemoryResourceHandler : ResourceHandler
{
public List<Tuple<Stream, Resource>> Streams;
public MemoryResourceHandler()
{
Streams = new List<Tuple<Stream, Resource>>();
}
public override void HandleResource(Resource resource, ResourceHandlingContext context)
{
MemoryStream outputStream = new MemoryStream();
Streams.Add(Tuple.Create<Stream, Resource>(outputStream, resource));
resource
.WithOutputUrl(new Url(Path.GetFileName(resource.OriginalUrl.Pathname), "memory:///"))
.Save(outputStream, context);
}
public void PrintInfo()
{
foreach (Tuple<Stream, Resource> stream in Streams)
Console.WriteLine($"uri:{stream.Item2.OutputUrl}, length:{stream.Item1.Length}");
}
}
// Modify SVG path data selected with CSS selectors in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-using-css-selectors/
// Load an SVG document
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "owl-svg-eyes.svg")))
{
SVGSVGElement svgElement = document.RootElement;
// Get a path for owl's body from the first <g> element
Element bodyPath = (svgElement.QuerySelector("g:first-child") as SVGGElement).FirstElementChild;
bodyPath.SetAttribute("stroke", "Teal");
// Get a path for the owl's wing from the first <g> element
SVGPathElement wingPath = svgElement.QuerySelector("g:first-child > path:nth-child(2)") as SVGPathElement;
// Form new wing path data based on the old
string d = "";
foreach (SVGPathSeg pathSeg in wingPath.PathSegList)
{
if (pathSeg is SVGPathSegMovetoAbs)
{
SVGPathSegMovetoAbs pathSegMovetoAbs = pathSeg as SVGPathSegMovetoAbs;
d += string.Format(" M {0} {1}", pathSegMovetoAbs.X, pathSegMovetoAbs.Y);
}
if (pathSeg is SVGPathSegCurvetoCubicAbs)
{
SVGPathSegCurvetoCubicAbs pathSegCurvetoCubicAbs = pathSeg as SVGPathSegCurvetoCubicAbs;
d += string.Format(
" L {0} {1} L {2} {3}",
(pathSegCurvetoCubicAbs.X1 + pathSegCurvetoCubicAbs.X2) / 2F,
(pathSegCurvetoCubicAbs.Y1 + pathSegCurvetoCubicAbs.Y2) / 2F,
pathSegCurvetoCubicAbs.X,
pathSegCurvetoCubicAbs.Y
);
}
}
// Set d attribute - new path data formation
wingPath.SetAttribute("d", d.Trim());
wingPath.SetAttribute("stroke", "Teal");
document.Save(Path.Combine(OutputDir, "owl-edited2.svg"));
}
// Navigate SVG with XPath in C#
// Learn more: https://docs.aspose.com/svg/net/navigation-inspection/
string inputPath = Path.Combine(DataDir, "shapes.svg");
using (SVGDocument document = new SVGDocument(inputPath))
{
// Evaluate the XPath expression against the SVG document
IXPathResult result = document.Evaluate(
"//rect[@x='120']",
document,
null,
Dom.XPath.XPathResultType.Any,
null);
// Read the first matching node
Element selectedElement = result.IterateNext() as Element;
if (selectedElement == null)
{
Console.WriteLine("No rectangle with x=\"120\" was found.");
return;
}
Console.WriteLine(selectedElement.OuterHTML);
}
// Implement a custom NodeFilter to select SVG rectangle elements in C#
// Learn more: https://docs.aspose.com/svg/net/navigation-inspection/
public class RectFilter : NodeFilter
{
public override short AcceptNode(Node n)
{
return string.Equals("rect", n.NodeName) ? FILTER_ACCEPT : FILTER_REJECT;
}
}
// Replace SVG circles with rectangles using CSS selectors in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-using-css-selectors/
// Load an SVG document
using (SVGDocument document = new SVGDocument(new Url("https://docs.aspose.com/svg/files/owl.svg")))
{
// Get the root <svg> element of the document
SVGSVGElement svgElement = document.RootElement;
// Create a new <g> element with style attributes and append it as the last child of the <svg> element
SVGGElement gElement = (SVGGElement)document.CreateElementNS(SvgNamespace, "g");
gElement.SetAttribute("fill", "none");
gElement.SetAttribute("stroke-width", "2");
svgElement.AppendChild(gElement);
// Find all <circle> elements from the first <g> element
NodeList circleNodes = svgElement.QuerySelectorAll("g:first-child > circle");
// Make square sky-blue eyes
foreach (Node circleNode in circleNodes)
{
SVGCircleElement circleElement = circleNode as SVGCircleElement;
float cx = circleElement.Cx.BaseVal.Value;
float cy = circleElement.Cy.BaseVal.Value;
float r = circleElement.R.BaseVal.Value;
SVGRectElement rectElement = (SVGRectElement)document.CreateElementNS(SvgNamespace, "rect");
rectElement.X.BaseVal.Value = cx - r;
rectElement.Y.BaseVal.Value = cy - r;
rectElement.Width.BaseVal.Value = 3 * r;
rectElement.Height.BaseVal.Value = 3 * r;
rectElement.SetAttribute("stroke", "SkyBlue");
// Add a <rectangle> element into the second (new) <g> element and remove <circle> elements
gElement.AppendChild(rectElement);
circleElement.Remove();
}
// Recolor last rectangle in the second (new) <g> element
Element lastRect = gElement.LastElementChild;
lastRect.SetAttribute("stroke", "red");
document.Save(Path.Combine(OutputDir, "owl-svg-eyes.svg"));
}
// Convert multiple SVGZ files to SVG format in C#
// Learn more: https://docs.aspose.com/svg/net/convert-svgz-to-svg/
// Loop through all .svgz files in the input directory
foreach (string svgzFile in Directory.GetFiles(DataDir, "*.svgz"))
{
try
{
// Extract the file name without extension to use for the output file
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(svgzFile);
// Construct the output path with .svg extension
string outputPath = Path.Combine(OutputDir, fileNameWithoutExt + ".svg");
// Load the compressed SVGZ file
using (SVGDocument document = new SVGDocument(svgzFile))
{
// Save it as a standard uncompressed SVG file
document.Save(outputPath, SVGSaveFormat.SVG);
}
// Log successful conversion
Console.WriteLine($"Converted: {fileNameWithoutExt}.svgz → {fileNameWithoutExt}.svg");
}
catch (Exception ex)
{
// Log any errors that occurred during conversion
Console.WriteLine($"Failed to convert {svgzFile}: {ex.Message}");
}
}
// Save an SVG document as a compressed SVGZ file in C#
// Learn more: https://docs.aspose.com/svg/net/save-svg-document/
// Set a full path to save the SVG document
Url url = new Url(Path.Combine(OutputUrl, "aspose.svgz"), Directory.GetCurrentDirectory());
// Load the SVG document from a file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "aspose.svg")))
{
// Work with the document
// Save the document to a URL in SVGZ format
document.Save(url, SVGSaveFormat.SVGZ);
}
// Save an SVG document to a file in C#
// Learn more: https://docs.aspose.com/svg/net/save-svg-document/
// Prepare a path to save an SVG document
string documentPath = Path.Combine(OutputDir, "circles_out.svg");
// Load the SVG document from a file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "circles.svg")))
{
// Work with the document
// Save SVG to a file
document.Save(documentPath);
}
// Save an SVG document to a URL in C#
// Learn more: https://docs.aspose.com/svg/net/save-svg-document/
// Set a full path for saving an SVG document
Url url = new Url(Path.Combine(OutputUrl, "lineto_out.svg"), Directory.GetCurrentDirectory());
// Load the SVG document from a file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "lineto.svg")))
{
// Work with the document
// Save the document to a URL
document.Save(url);
}
// Save an SVG document with external resources to a ZIP archive in C#
// Learn more: https://docs.aspose.com/svg/net/save-svg-document/
// Prepare a path to a source SVG file
string inputPath = Path.Combine(DataDir, "with-resources.svg");
string dir = Directory.GetCurrentDirectory();
// Prepare a full path to an output ZIP archive
string customArchivePath = Path.Combine(dir, "./../../../../tests-out/saving/archive.zip");
// Load an SVG document
using (SVGDocument doc = new SVGDocument(inputPath))
{
// Initialize an instance of the ZipResourceHandler class
using (ZipResourceHandler resourceHandler = new ZipResourceHandler(customArchivePath))
{
// Save SVG with resources to a ZIP archive
doc.Save(resourceHandler);
}
}
// Save an SVG document and its resources to memory streams in C#
// Learn more: https://docs.aspose.com/svg/net/save-svg-document/
// Prepare a path to a source SVG file
string inputPath = Path.Combine(DataDir, "with-resources.svg");
// Initialize an SVG document
using (SVGDocument doc = new SVGDocument(inputPath))
{
// Create an instance of the MemoryResourceHandler class and save SVG to memory
MemoryResourceHandler resourceHandler = new MemoryResourceHandler();
doc.Save(resourceHandler);
resourceHandler.PrintInfo();
}
// Save an SVG document with external resources to local storage in C#
// Learn more: https://docs.aspose.com/svg/net/save-svg-document/
// Prepare a path to a source SVG file
string inputPath = Path.Combine(DataDir, "with-resources.svg");
// Prepare a full path to an output directory
string customOutDir = Path.Combine(Directory.GetCurrentDirectory(), "./../../../../tests-out/saving/");
// Load an SVG document from a file
using (SVGDocument doc = new SVGDocument(inputPath))
{
// Save SVG with resources
doc.Save(new FileSystemResourceHandler(customOutDir));
}
// Draw SVG shapes and text on an existing bitmap in C#
// Learn more: https://docs.aspose.com/svg/net/edit-svg-file/
// Set the SVG namespace URI
string SvgNamespace = "http://www.w3.org/2000/svg";
using (SVGDocument document = new SVGDocument())
{
SVGSVGElement svgElement = document.RootElement;
// Create an <image> element and add it into svgElement
SVGImageElement imageElement = (SVGImageElement)document.CreateElementNS(SvgNamespace, "image");
imageElement.Href.BaseVal = "http://docs.aspose.com/svg/images/api/seaside.jpg";
imageElement.Height.BaseVal.ConvertToSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX);
imageElement.Width.BaseVal.ConvertToSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX);
imageElement.Height.BaseVal.Value = 480;
imageElement.Width.BaseVal.Value = 640;
imageElement.X.BaseVal.Value = 20;
imageElement.Y.BaseVal.Value = 20;
svgElement.AppendChild(imageElement);
// Create a <text> element, set its attributes, and add it to the <svg> element
SVGTextElement textElement = (SVGTextElement)document.CreateElementNS(SvgNamespace, "text");
textElement.Style.FontSize = "1.4em";
textElement.SetAttribute("x", "420px");
textElement.SetAttribute("fill", "gold");
textElement.SetAttribute("y", "280px");
textElement.TextContent = "The beach is beautiful...";
svgElement.AppendChild(textElement);
// Create a <circle> element, set its attributes, and add it to the <svg> element
SVGCircleElement circleElement = (SVGCircleElement)document.CreateElementNS(SvgNamespace, "circle");
circleElement.Cx.BaseVal.Value = 520;
circleElement.Cy.BaseVal.Value = 120;
circleElement.R.BaseVal.Value = 60;
circleElement.SetAttribute("stroke", "gold");
circleElement.SetAttribute("stroke-width", "70");
circleElement.SetAttribute("fill", "none");
circleElement.SetAttribute("stroke-dasharray", "2,14");
svgElement.AppendChild(circleElement);
// Save the document
document.Save(Path.Combine(OutputDir, "svg-drawing-on-bitmap.svg"));
}
// Traverse SVG document elements using the DOM in C#
// Learn more: https://docs.aspose.com/svg/net/navigation-inspection/
// Load an SVG document
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "shapes_svg.svg")))
{
// Get direct access to the <svg> element of the document
Element element = document.DocumentElement;
Console.WriteLine(element.TagName); // svg
// Use the LastElementChild property
element = element.LastElementChild;
Console.WriteLine(element.TagName); // g
// Use the FirstElementChild property
element = element.FirstElementChild;
Console.WriteLine(element.TagName); // rect
}
// View SVG document content as OuterHTML in C#
// Learn more: https://docs.aspose.com/svg/net/navigation-inspection/
// Load an SVG document
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "bezier-curves.svg")))
{
// Use the OuterHTML property
string html = document.DocumentElement.OuterHTML;
Console.WriteLine(html);
}
// View the document content
// Implement a resource handler to package SVG resources in a ZIP archive in C#
// Learn more: https://docs.aspose.com/svg/net/save-svg-document/
internal class ZipResourceHandler : ResourceHandler, IDisposable
{
private FileStream zipStream;
private ZipArchive archive;
private int streamsCounter;
private bool initialized;
public ZipResourceHandler(string name)
{
DisposeArchive();
zipStream = new FileStream(name, FileMode.Create);
archive = new ZipArchive(zipStream, ZipArchiveMode.Update);
initialized = false;
}
public override void HandleResource(Resource resource, ResourceHandlingContext context)
{
string zipUri = (streamsCounter++ == 0
? Path.GetFileName(resource.OriginalUrl.Href)
: Path.Combine(Path.GetFileName(Path.GetDirectoryName(resource.OriginalUrl.Href)),
Path.GetFileName(resource.OriginalUrl.Href)));
string samplePrefix = String.Empty;
if (initialized)
samplePrefix = "my_";
else
initialized = true;
using (Stream newStream = archive.CreateEntry(samplePrefix + zipUri).Open())
{
resource.WithOutputUrl(new Url("file:///" + samplePrefix + zipUri)).Save(newStream, context);
}
}
private void DisposeArchive()
{
if (archive != null)
{
archive.Dispose();
archive = null;
}
if (zipStream != null)
{
zipStream.Dispose();
zipStream = null;
}
streamsCounter = 0;
}
public void Dispose()
{
DisposeArchive();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment