Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

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

Select an option

Save aspose-com-gists/dd1bd43f1e4b055cf52f4bfe351e54de to your computer and use it in GitHub Desktop.
This Gist contains C# examples Aspose.SVG for .NET – Working with SVG Colors

Aspose.SVG for .NET – Work with SVG Colors in C#

This GitHub gist repository contains practical C# code snippets from the Working With SVG Colors in C# chapter of Aspose.SVG for .NET documentation. The examples show how to change SVG fill and stroke colors, add or update SVG background colors, work with CSS color declarations, replace SVG color palettes, extract colors from SVG files, control opacity and transparency, edit gradient colors, and convert color codes such as HEX, RGB, RGBA, HSL, and CMYK.

Topics Covered

  • Change SVG Element Colors – Update fill, stroke, and other presentation attributes for shapes such as <circle>, <line>, <path>, and <rect>.
  • Add and Change SVG Background Color – Insert a background <rect>, update an existing background element, or create an SVG document with a custom background color.
  • Apply SVG Colors with CSS – Use inline style attributes and internal <style> elements to define SVG fills, strokes, and background colors.
  • Use JavaScript for SVG Background Color – Append a <script> element that dynamically adds a background rectangle to an SVG document.
  • Replace SVG Colors – Replace colors in fill, stroke, stop-color, and inline CSS declarations, including palette-based color replacement.
  • Extract SVG Colors – Collect unique colors from SVG attributes, inline styles, and gradient stops for inspection or auditing.
  • Normalize Color Values – Convert color names, HEX values, RGB values, LAB values, and other color formats to consistent output formats.
  • Control SVG Opacity and Transparency – Set opacity, fill-opacity, stroke-opacity, RGBA colors, HSLA colors, and transparent export backgrounds.
  • Change SVG Gradient Colors – Update linear and radial gradient stops, replace all gradient stop colors, and repoint fill="url(#id)" to another gradient.
  • Save and Export Edited SVG Files – Save modified SVG documents and export edited color or gradient results to formats such as PNG and PDF.
  • Modify SVG Styles with the DOM API – Create gradients, filters, shapes, text, and inline styles programmatically.

How to Use These Examples

  1. Create a C# project and add the Aspose.SVG for .NET package via NuGet.
  2. Locate the example that matches your SVG color task.
  3. Adjust input file paths, output paths, color values, selectors, and gradient IDs as needed.
  4. Run the code to review the output SVG, PNG, or PDF files and verify the applied color changes.

You can use a temporary license to evaluate Aspose.SVG for .NET without evaluation limitations.

About Aspose.SVG for .NET

Aspose.SVG for .NET is a cross-platform C# library for creating, editing, converting, and rendering SVG files on Windows, Linux, and macOS. It provides DOM APIs for working with SVG elements, attributes, styles, gradients, filters, and text. The library also includes color parsing and conversion features that help normalize color values and prepare SVG files for rendering, export, or automated processing.

Resources & Support

Prerequisites

  • .NET Framework 4.6.1+, .NET Core 2.0+, or .NET 5+.
  • Windows, Linux, or macOS.
  • A development environment such as Visual Studio, Visual Studio Code, or JetBrains Rider.
  • Aspose.SVG for .NET installed via NuGet.
Aspose.SVG for .NET – Working with SVG Colors
// Add a background color rectangle to an existing SVG in C#
// Learn more: https://docs.aspose.com/svg/net/change-svg-background-color/
// Load an SVG document from a file
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "tree.svg"));
// Get the root SVG element of the document
SVGSVGElement svgElement = document.RootElement;
// Create a rectangle element and set attributes values
SVGRectElement rectElement = (SVGRectElement)document.CreateElementNS("http://www.w3.org/2000/svg", "rect");
rectElement.X.BaseVal.Value = 3;
rectElement.Y.BaseVal.Value = 3;
rectElement.SetAttribute("width", "100%");
rectElement.SetAttribute("height", "100%");
rectElement.SetAttribute("fill", "#ebf3f6");
// Add the rectangle element as the first child to <svg> element
svgElement.InsertBefore(rectElement, svgElement.FirstChild);
// Save the SVG document
document.Save(Path.Combine(OutputDir, "add-background-color.svg"));
// Add an SVG background color using a CSS style element and class in C#
// Learn more: https://docs.aspose.com/svg/net/change-svg-background-color/
// Set SVG Namespace URL
string SvgNamespace = "http://www.w3.org/2000/svg";
// Load an SVG document from a file
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "tulips.svg"));
// Get the root <svg> element of the document
SVGSVGElement svgElement = document.RootElement;
// Create a <style> element
SVGStyleElement styleElement = (SVGStyleElement)document.CreateElementNS(SvgNamespace, "style");
// Set the CSS content to define a background color class
styleElement.TextContent = @".background {fill: grey;}";
// Insert the <style> element at the beginning of the <svg> element
svgElement.InsertBefore(styleElement, svgElement.FirstChild);
// Create a rectangle element and set the class to "background"
SVGRectElement rectElement = (SVGRectElement)document.CreateElementNS(SvgNamespace, "rect");
rectElement.X.BaseVal.Value = -120;
rectElement.Y.BaseVal.Value = 0;
rectElement.SetAttribute("width", "100%");
rectElement.SetAttribute("height", "100%");
rectElement.SetAttribute("class", "background");
// Add the rectangle element as the first child to the <svg> element, after the <style> element
svgElement.InsertBefore(rectElement, svgElement.ChildNodes[1]);
// Save the SVG document
document.Save(Path.Combine(OutputDir, "add-background-color-with-css.svg"));
// Apply RGBA and HSLA transparent colors to SVG fill and stroke in C#
// Learn more: https://docs.aspose.com/svg/net/svg-opacity-and-transparent-colors/
// Load the source SVG file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "svg-opacity.svg")))
{
// Select the path that will receive transparent color values
Element wave = document.QuerySelector("#wave");
// Apply transparent color values directly to fill and stroke
wave.SetAttribute("fill", "rgba(0, 119, 230, 0.35)");
wave.SetAttribute("stroke", "hsla(209, 100%, 45%, 0.65)");
// Save the SVG with RGBA and HSLA transparent colors
document.Save(Path.Combine(OutputDir, "svg-rgba-hsla-opacity.svg"));
}
// Build a unique SVG color palette from attributes and inline styles in C#
// Learn more: https://docs.aspose.com/svg/net/extract-svg-colors/
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
{
string[] colorAttributes = { "fill", "stroke", "stop-color" };
HashSet<string> colorProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"fill",
"stroke",
"color",
"stop-color"
};
SortedSet<string> palette = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
// Collect direct color values from SVG presentation attributes
foreach (Element element in document.QuerySelectorAll("*"))
{
foreach (string attributeName in colorAttributes)
{
string value = element.GetAttribute(attributeName);
if (string.IsNullOrWhiteSpace(value))
{
continue;
}
string color = value.Trim();
if (!color.Equals("none", StringComparison.OrdinalIgnoreCase) &&
!color.Equals("currentColor", StringComparison.OrdinalIgnoreCase) &&
!color.StartsWith("url(", StringComparison.OrdinalIgnoreCase))
{
palette.Add(color);
}
}
}
// Collect direct color values from inline CSS declarations
foreach (Element element in document.QuerySelectorAll("[style]"))
{
string style = element.GetAttribute("style");
foreach (string declaration in style.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
string[] parts = declaration.Split(':', 2);
if (parts.Length != 2)
{
continue;
}
string property = parts[0].Trim();
string value = parts[1].Trim();
if (colorProperties.Contains(property) &&
!value.Equals("none", StringComparison.OrdinalIgnoreCase) &&
!value.Equals("currentColor", StringComparison.OrdinalIgnoreCase) &&
!value.StartsWith("url(", StringComparison.OrdinalIgnoreCase))
{
palette.Add(value);
}
}
}
// Print the complete unique SVG color palette
foreach (string color in palette)
{
Console.WriteLine(color);
}
}
// Add a colored background and recolor SVG path strokes using C# DOM methods
// Learn more: https://docs.aspose.com/svg/net/how-to-change-svg-color/
// Set SVG Namespace Url
string SvgNamespace = "http://www.w3.org/2000/svg";
// Load an SVG document from a file
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "snowflake-blue.svg"));
// Get the root SVG element of the document
SVGSVGElement svgElement = document.RootElement;
// Create a <circle> element and set attributes values
SVGCircleElement circleElement = (SVGCircleElement)document.CreateElementNS(SvgNamespace, "circle");
circleElement.Cx.BaseVal.Value = 150F;
circleElement.Cy.BaseVal.Value = 100F;
circleElement.R.BaseVal.Value = 150F;
circleElement.SetAttribute("fill", "#03b6fd");
// Add the <circle> element (background) as the first child to <svg> element
svgElement.InsertBefore(circleElement, svgElement.FirstChild);
// Get the first <path> element to change color
SVGPathElement snowflakePath = svgElement.QuerySelector("path") as SVGPathElement;
// Set a new "stroke" attribute value for the <path> element
snowflakePath.SetAttribute("stroke", "white");
// Save the SVG document
document.Save(Path.Combine(OutputDir, "recolor-svg.svg"));
// Change the background color of an SVG image by adding a rectangle in C#
// Learn more: https://docs.aspose.com/svg/net/how-to-change-svg-color/
// Load an SVG document from a file
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "basic-shapes.svg"));
// Get the root SVG element of the document
SVGSVGElement svgElement = document.RootElement;
// Create a rectangle element and set the "fill" attribute value to change background color
SVGRectElement rectElement = (SVGRectElement)document.CreateElementNS("http://www.w3.org/2000/svg", "rect");
rectElement.X.BaseVal.Value = 3;
rectElement.Y.BaseVal.Value = 3;
rectElement.Width.BaseVal.Value = 400;
rectElement.Height.BaseVal.Value = 400;
rectElement.SetAttribute("fill", "Salmon");
// Add the rectangle element as the first child to <svg> element
svgElement.InsertBefore(rectElement, svgElement.FirstChild);
// Save the SVG document
document.Save(Path.Combine(OutputDir, "change-background-color.svg"));
// Change the fill color of an existing SVG background rectangle in C#
// Learn more: https://docs.aspose.com/svg/net/change-svg-background-color/
// Load an SVG document from a file
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "add-background-color.svg"));
// Get the root SVG element of the document
SVGSVGElement svgElement = document.RootElement;
// Get the first <rect> element to change color
SVGRectElement rectElement = svgElement.QuerySelector("rect") as SVGRectElement;
// Set a new "fill" attribute value for the <rect> element
rectElement.SetAttribute("fill", "#fef4fd");
// Save the SVG document
document.Save(Path.Combine(OutputDir, "change-background-color-in.svg"));
// Set the SVG background color using the style attribute in C#
// Learn more: https://docs.aspose.com/svg/net/change-svg-background-color/
// Prepare a path to a source SVG file
string documentPath = Path.Combine(DataDir, "tulips.svg");
// Load an SVG document from the file
SVGDocument document = new SVGDocument(documentPath);
// Get the root SVG element of the document
SVGSVGElement svgElement = document.RootElement;
// Create a style attribute for the <svg> element
svgElement.SetAttribute("style", "background: grey");
// Save the SVG document
document.Save(Path.Combine(OutputDir, "with-background-color.svg"));
// Change linear gradient stop colors in an SVG file using C#
// Learn more: https://docs.aspose.com/svg/net/change-gradient-colors/
// Load an SVG file that contains a linear gradient
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "linear-gradient.svg")))
{
// Find the linearGradient element by ID
Element gradient = document.QuerySelector("linearGradient#grad1");
if (gradient == null)
{
throw new InvalidOperationException("Gradient 'grad1' was not found.");
}
// Define replacement colors for the linear gradient stops
string[] newColors =
{
"#1565c0",
"#00acc1",
"#f9a825"
};
int index = 0;
// Update each stop in the selected linear gradient
foreach (Element stop in gradient.QuerySelectorAll("stop"))
{
if (index >= newColors.Length)
{
break;
}
// Write stop-color as a presentation attribute
stop.SetAttribute("stop-color", newColors[index]);
// Remove a conflicting inline stop-color declaration if the source SVG used style
string style = stop.GetAttribute("style");
if (!string.IsNullOrWhiteSpace(style) &&
style.IndexOf("stop-color", StringComparison.OrdinalIgnoreCase) >= 0)
{
stop.RemoveAttribute("style");
}
index++;
}
// Save the SVG file with changed linear gradient colors
document.Save(Path.Combine(OutputDir, "linear-gradient-recolored.svg"));
}
// Change the opacity of an SVG group element in C#
// Learn more: https://docs.aspose.com/svg/net/svg-opacity-and-transparent-colors/
// Load the source SVG file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "svg-opacity.svg")))
{
// Select a group whose fill, stroke, and child elements should fade together
Element badge = document.QuerySelector("#badge");
// Set opacity for the entire selected SVG group
badge.SetAttribute("opacity", "0.45");
// Save the SVG with updated element opacity
document.Save(Path.Combine(OutputDir, "svg-opacity-element.svg"));
}
// Change radial gradient stop colors in an SVG file using C#
// Learn more: https://docs.aspose.com/svg/net/change-gradient-colors/
// Load an SVG file that contains a radial gradient
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "radial-gradient.svg")))
{
// Find the radialGradient element by ID
Element gradient = document.QuerySelector("radialGradient#myRG");
if (gradient == null)
{
throw new InvalidOperationException("Gradient 'myRG' was not found.");
}
// Map gradient offsets to new stop colors
Dictionary<string, string> colorsByOffset = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["0%"] = "#fce1ff",
["60%"] = "#690058"
};
// Update only the gradient stops whose offsets are listed in the palette
foreach (Element stop in gradient.QuerySelectorAll("stop"))
{
string offset = stop.GetAttribute("offset").Trim();
if (colorsByOffset.TryGetValue(offset, out string newColor))
{
stop.SetAttribute("stop-color", newColor);
}
}
// Save the SVG file with changed radial gradient colors
document.Save(Path.Combine(OutputDir, "radial-gradient-recolored.svg"));
}
// Change a background color for an SVG document using SVG Builder
// Learn more: https://docs.aspose.com/svg/net/change-svg-background-color/
// Initialize an SVG document
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "tulips.svg")))
{
SVGSVGElement svg = new SVGSVGElementBuilder()
.Width(100, LengthType.Percentage)
.Height(100, LengthType.Percentage)
.Build(document.FirstChild as SVGSVGElement);
// Create a new <g> element using SVGGElementBuilder and add <style> and <rect> elements to it
SVGElement g = new SVGGElementBuilder()
.Id("background")
.AddStyle(style => style
.Type("text/css")
.AddRule(".background", r => r.Fill(System.Drawing.Color.Gray))
)
.AddRect(rect => rect
.X(-120).Y(0).Width(100, LengthType.Percentage).Height(100, LengthType.Percentage)
.Class("background")
).BuildElement(document);
svg.InsertBefore(g, svg.FirstElementChild);
// Save the document
document.Save(Path.Combine(OutputDir, "add-background-color-with-builder.svg"));
}
// Add an SVG background color using an embedded JavaScript element in C#
// Learn more: https://docs.aspose.com/svg/net/change-svg-background-color/
// Load an SVG document from a file
SVGDocument document = new SVGDocument(Path.Combine(DataDir, "tree.svg"));
// Get the root <svg> element of the document
SVGSVGElement svgElement = document.RootElement;
// Create a new <script> element
Element scriptElement = document.CreateElementNS("http://www.w3.org/2000/svg", "script");
// Define JavaScript code to add a <rect> element as the background
scriptElement.TextContent = @"
var svgElement = document.getElementsByTagName('svg')[0];
if (svgElement) {
var rectElement = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rectElement.setAttribute('x', '0');
rectElement.setAttribute('y', '0');
rectElement.setAttribute('width', '100%');
rectElement.setAttribute('height', '100%');
rectElement.setAttribute('fill', '#fef4fd');
svgElement.insertBefore(rectElement, svgElement.firstChild);
};
";
// Append the <script> element to the SVG document
svgElement.AppendChild(scriptElement);
// Save the modified SVG document
document.Save(Path.Combine(OutputDir, "svg-background-color-using-script.svg"));
// Change the fill color of an SVG circle in C#
// Learn more: https://docs.aspose.com/svg/net/how-to-change-svg-color/
// Prepare a path to a file loading
string documentPath = Path.Combine(DataDir, "basic-shapes.svg");
// Load an SVG document from the file
SVGDocument document = new SVGDocument(documentPath);
// Get the root SVG element of the document
SVGSVGElement svgElement = document.RootElement;
// Get a <circle> element to change a color
SVGCircleElement circleElement = svgElement.QuerySelector("circle") as SVGCircleElement;
// Set a new "fill" attribute value for the circle element
circleElement.SetAttribute("fill", "green");
// Save the SVG document to a file
document.Save(Path.Combine(OutputDir, "circle-color.svg"));
// Change the stroke color of an SVG line using QuerySelector and SetAttribute in C#
// Learn more: https://docs.aspose.com/svg/net/how-to-change-svg-color/
// Prepare a path to a file loading
string documentPath = Path.Combine(DataDir, "basic-shapes.svg");
// Load an SVG document from the file
SVGDocument document = new SVGDocument(documentPath);
// Get the root SVG element of the document
SVGSVGElement svgElement = document.RootElement;
// Get a <line> element to change color
SVGLineElement lineElement = svgElement.QuerySelector("line") as SVGLineElement;
// Set a new "stroke" attribute value for the <line> element
lineElement.SetAttribute("stroke", "green");
// Save the SVG document
document.Save(Path.Combine(OutputDir, "line-color.svg"));
// Convert a named color value to HEX format in C#
// Learn more: https://docs.aspose.com/svg/net/convert-color-codes/
// Parse a named color from a string
Color color = Color.FromString("black");
// Convert named color to HEX
string hexColor = color.ToRgbHexString();
// Print result to console
Console.WriteLine(hexColor);
// Result: #000000
// Convert a HEX color value to RGB format in C#
// Learn more: https://docs.aspose.com/svg/net/convert-color-codes/
// Parse HEX color from a string
Color color = Color.FromString("#ff31ca");
// Convert HEX to RGB
string rgbColor = color.ToRgbString();
// Print result to console
Console.WriteLine(rgbColor);
// Result: rgb(255, 49, 202)
// Convert an HSL color value to HEX format in C#
// Learn more: https://docs.aspose.com/svg/net/convert-color-codes/
// Parse HSL color from a string
Color color = Color.FromString("hsl(315, 100%, 60%)");
// Convert HSL to HEX
string hexColor = color.ToRgbHexString();
// Print result to console
Console.WriteLine(hexColor);
// Result: #FF33CC
// Convert LAB to CMYK in C#
// Learn more: https://docs.aspose.com/svg/net/convert-color-codes/
// Parse LAB color from a string
Color color = Color.FromLab(51.788f, 62.357f, 52.178f);
// Convert LAB to CMYK
string cmykColor = color.Convert(ColorModel.Cmyk).ToString(false, false, 0);
// Print result to console
Console.WriteLine(cmykColor);
// Result: cmyk(0%, 73%, 84%, 12%)
// Convert an RGBA color value to 8-digit HEX format in C#
// Learn more: https://docs.aspose.com/svg/net/convert-color-codes/
// Parse RGBA color from a string
Color color = Color.FromString("rgba(255, 49, 202, 0.5)");
// Convert RGBA to 8-digit HEX
Console.WriteLine(color.ToRgbaHexString());
// Result: #FF31CA7F
// Convert an RGB color value to HEX format in C#
// Learn more: https://docs.aspose.com/svg/net/convert-color-codes/
// Parse RGB color from a string
Color color = Color.FromString("rgb(255, 49, 202)");
// Convert RGB to HEX
string hexColor = color.ToRgbHexString();
// Print result to console
Console.WriteLine(hexColor);
// Result: #FF31CA
// Create the same red color from RGB, HSL, and CMYK components in C#
// Learn more: https://docs.aspose.com/svg/net/convert-color-codes/
// Create a color from RGB components
Color rgbColor = Color.FromRgb(255, 0, 0);
// Create a color from HSL components
Color hslColor = Color.FromHsl(0, 1, 0.5f);
// Create a color from CMYK components
Color cmykColor = Color.FromCmyk(0, 1, 1, 0);
// Print converted color values to console
Console.WriteLine(rgbColor.ToRgbHexString());
Console.WriteLine(hslColor.ToRgbString());
Console.WriteLine(cmykColor.ToRgbHexString());
// Result:
// #FF0000
// rgb(255, 0, 0)
// #FF0000
// Create an SVG file with a background color and colored shapes in C#
// Learn more: https://docs.aspose.com/svg/net/change-svg-background-color/
// Create a new SVG document from scratch
using (SVGDocument document = new SVGDocument())
{
// Get the root <svg> element and define the canvas size
SVGSVGElement svgElement = document.RootElement;
svgElement.SetAttribute("style", "background-color: lightblue;");
svgElement.SetAttribute("width", "800");
svgElement.SetAttribute("height", "600");
svgElement.SetAttribute("viewBox", "0 0 800 600");
// Add a rectangle that works as the visible SVG background
Element background = document.CreateElementNS("http://www.w3.org/2000/svg", "rect");
background.SetAttribute("x", "0");
background.SetAttribute("y", "0");
background.SetAttribute("width", "100%");
background.SetAttribute("height", "100%");
background.SetAttribute("fill", "#d7efff");
svgElement.AppendChild(background);
// Add a filled rectangle with an outline
Element rect = document.CreateElementNS("http://www.w3.org/2000/svg", "rect");
rect.SetAttribute("x", "60");
rect.SetAttribute("y", "70");
rect.SetAttribute("width", "280");
rect.SetAttribute("height", "180");
rect.SetAttribute("fill", "#ffd54f");
rect.SetAttribute("stroke", "#f57f17");
rect.SetAttribute("stroke-width", "4");
svgElement.AppendChild(rect);
// Add a circle with a separate fill and stroke color
Element circle = document.CreateElementNS("http://www.w3.org/2000/svg", "circle");
circle.SetAttribute("cx", "520");
circle.SetAttribute("cy", "220");
circle.SetAttribute("r", "90");
circle.SetAttribute("fill", "#ff6b6b");
circle.SetAttribute("stroke", "#8b1a1a");
circle.SetAttribute("stroke-width", "4");
svgElement.AppendChild(circle);
// Add a polygon-like path to complete the SVG composition
Element path = document.CreateElementNS("http://www.w3.org/2000/svg", "path");
path.SetAttribute("d", "M 220 410 L 360 320 L 500 410 L 430 510 L 290 510 Z");
path.SetAttribute("fill", "#6495ed");
path.SetAttribute("stroke", "#1d3f8a");
path.SetAttribute("stroke-width", "3");
svgElement.AppendChild(path);
// Save the SVG document to file
document.Save(Path.Combine(OutputDir, "background-color.svg"));
}
// Export SVG to PNG and PDF with a transparent background in C#
// Learn more: https://docs.aspose.com/svg/net/svg-opacity-and-transparent-colors/
// Load an SVG that does not contain a background rectangle
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "svg-opacity.svg")))
{
// PNG supports alpha transparency. BackgroundColor is transparent by default,
// but setting it explicitly documents the intended output behavior
ImageSaveOptions pngOptions = new ImageSaveOptions
{
BackgroundColor = System.Drawing.Color.Transparent
};
// Convert SVG to PNG while preserving the transparent background
Converter.ConvertSVG(document, pngOptions, Path.Combine(OutputDir, "svg-transparent-background.png"));
// PDF output can also avoid filling the page background
PdfSaveOptions pdfOptions = new PdfSaveOptions
{
BackgroundColor = System.Drawing.Color.Transparent
};
// Convert SVG to PDF while preserving the transparent background
Converter.ConvertSVG(document, pdfOptions, Path.Combine(OutputDir, "svg-transparent-background.pdf"));
}
// Extract SVG colors from inline CSS style attributes in C#
// Learn more: https://docs.aspose.com/svg/net/extract-svg-colors/
// Load the source SVG file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
{
// Inspect CSS properties that commonly store visible SVG colors
HashSet<string> colorProperties = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"fill",
"stroke",
"color",
"stop-color"
};
SortedSet<string> colors = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
// Select only elements with inline style attributes
foreach (Element element in document.QuerySelectorAll("[style]"))
{
string style = element.GetAttribute("style");
// Split the inline style into individual CSS declarations
foreach (string declaration in style.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
string[] parts = declaration.Split(':', 2);
if (parts.Length != 2)
{
continue;
}
string property = parts[0].Trim();
string value = parts[1].Trim();
if (!colorProperties.Contains(property))
{
continue;
}
// Skip paint keywords and paint server references that are not direct colors
if (value.Equals("none", StringComparison.OrdinalIgnoreCase) ||
value.Equals("currentColor", StringComparison.OrdinalIgnoreCase) ||
value.StartsWith("url(", StringComparison.OrdinalIgnoreCase))
{
continue;
}
colors.Add(value);
}
}
// Print the unique SVG colors found in inline styles
foreach (string color in colors)
{
Console.WriteLine(color);
}
}
// Extract unique SVG colors from fill, stroke, and stop-color attributes in C#
// Learn more: https://docs.aspose.com/svg/net/extract-svg-colors/
// Load the source SVG file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
{
// Inspect attributes that commonly store visible SVG colors
string[] colorAttributes = { "fill", "stroke", "stop-color" };
// Use a case-insensitive set to keep only unique color values
SortedSet<string> colors = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
// Find all SVG elements and read their color-related attributes
foreach (Element element in document.QuerySelectorAll("*"))
{
foreach (string attributeName in colorAttributes)
{
string value = element.GetAttribute(attributeName);
if (string.IsNullOrWhiteSpace(value))
{
continue;
}
string color = value.Trim();
// Skip paint keywords and paint server references that are not direct colors
if (color.Equals("none", StringComparison.OrdinalIgnoreCase) ||
color.Equals("currentColor", StringComparison.OrdinalIgnoreCase) ||
color.StartsWith("url(", StringComparison.OrdinalIgnoreCase))
{
continue;
}
colors.Add(color);
}
}
// Print the unique SVG colors found in attributes
foreach (string color in colors)
{
Console.WriteLine(color);
}
}
// Extract colors from SVG linear and radial gradient stops in C#
// Learn more: https://docs.aspose.com/svg/net/extract-svg-colors/
// Load the source SVG file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
{
SortedSet<string> gradientColors = new SortedSet<string>(StringComparer.OrdinalIgnoreCase);
// Select gradient stop elements that define stop-color values
foreach (Element stopElement in document.QuerySelectorAll("stop[stop-color]"))
{
string color = stopElement.GetAttribute("stop-color").Trim();
if (!string.IsNullOrWhiteSpace(color))
{
gradientColors.Add(color);
}
}
// Print the unique colors used in SVG gradient stops
foreach (string color in gradientColors)
{
Console.WriteLine(color);
}
}
// Modify SVG styles, gradients, filters, and shapes using the DOM API in C#
// Learn more: https://docs.aspose.com/svg/net/working-with-svg-colors/
// Create a new SVG document from scratch
using (SVGDocument document = new SVGDocument())
{
// Get the root <svg> element
SVGSVGElement svgElement = document.RootElement;
// Set SVG dimensions and viewBox
svgElement.SetAttribute("width", "800");
svgElement.SetAttribute("height", "600");
svgElement.SetAttribute("viewBox", "0 0 800 600");
// Create a <defs> section for reusable gradient and filter definitions
Element defsElement = document.CreateElementNS("http://www.w3.org/2000/svg", "defs");
svgElement.AppendChild(defsElement);
// Create a linear gradient that can be referenced by shape fills
Element linearGradient = document.CreateElementNS("http://www.w3.org/2000/svg", "linearGradient");
linearGradient.SetAttribute("id", "gradient1");
linearGradient.SetAttribute("x1", "0%");
linearGradient.SetAttribute("y1", "0%");
linearGradient.SetAttribute("x2", "100%");
linearGradient.SetAttribute("y2", "100%");
Element stop1 = document.CreateElementNS("http://www.w3.org/2000/svg", "stop");
stop1.SetAttribute("offset", "0%");
stop1.SetAttribute("stop-color", "#4fc3f7");
linearGradient.AppendChild(stop1);
Element stop2 = document.CreateElementNS("http://www.w3.org/2000/svg", "stop");
stop2.SetAttribute("offset", "100%");
stop2.SetAttribute("stop-color", "#0288d1");
linearGradient.AppendChild(stop2);
defsElement.AppendChild(linearGradient);
// Create a Gaussian blur filter that can be reused by shapes
Element filter = document.CreateElementNS("http://www.w3.org/2000/svg", "filter");
filter.SetAttribute("id", "blurFilter");
filter.SetAttribute("x", "0");
filter.SetAttribute("y", "0");
filter.SetAttribute("width", "200%");
filter.SetAttribute("height", "200%");
Element feGaussianBlur = document.CreateElementNS("http://www.w3.org/2000/svg", "feGaussianBlur");
feGaussianBlur.SetAttribute("in", "SourceGraphic");
feGaussianBlur.SetAttribute("stdDeviation", "10");
filter.AppendChild(feGaussianBlur);
defsElement.AppendChild(filter);
// Create a rectangle with gradient fill and a filter reference
Element rect = document.CreateElementNS("http://www.w3.org/2000/svg", "rect");
rect.SetAttribute("x", "50");
rect.SetAttribute("y", "50");
rect.SetAttribute("width", "300");
rect.SetAttribute("height", "200");
rect.SetAttribute("fill", "url(#gradient1)");
rect.SetAttribute("stroke", "#0d47a1");
rect.SetAttribute("stroke-width", "3");
rect.SetAttribute("rx", "15");
rect.SetAttribute("ry", "15");
rect.SetAttribute("filter", "url(#blurFilter)");
svgElement.AppendChild(rect);
// Create a circle and set multiple visual properties through an inline style
Element circle = document.CreateElementNS("http://www.w3.org/2000/svg", "circle");
circle.SetAttribute("cx", "550");
circle.SetAttribute("cy", "200");
circle.SetAttribute("r", "80");
circle.SetAttribute("style", "fill: #ff7043; stroke: #bf360c; stroke-width: 5; opacity: 0.85; filter: url(#blurFilter);");
svgElement.AppendChild(circle);
// Create a path with a dashed stroke and rounded line caps
Element path = document.CreateElementNS("http://www.w3.org/2000/svg", "path");
path.SetAttribute("d", "M 100 450 Q 250 350 400 450 T 700 450");
path.SetAttribute("fill", "none");
path.SetAttribute("stroke", "#388e3c");
path.SetAttribute("stroke-width", "8");
path.SetAttribute("stroke-dasharray", "20,10");
path.SetAttribute("stroke-linecap", "round");
path.SetAttribute("style", "opacity: 0.9;");
svgElement.AppendChild(path);
// Update the rectangle style after the element has already been added to the DOM
rect.SetAttribute("style", "fill: url(#gradient1); stroke: #0d47a1; stroke-width: 3; rx: 15; ry: 15; filter: url(#blurFilter); opacity: 0.95;");
// Add a styled background rectangle for the text label
Element textBg = document.CreateElementNS("http://www.w3.org/2000/svg", "rect");
textBg.SetAttribute("x", "300");
textBg.SetAttribute("y", "500");
textBg.SetAttribute("width", "200");
textBg.SetAttribute("height", "60");
textBg.SetAttribute("fill", "#fdd835");
textBg.SetAttribute("rx", "10");
textBg.SetAttribute("style", "filter: url(#blurFilter);");
svgElement.AppendChild(textBg);
// Add a text label with font and fill attributes
Element text = document.CreateElementNS("http://www.w3.org/2000/svg", "text");
text.SetAttribute("x", "400");
text.SetAttribute("y", "540");
text.SetAttribute("text-anchor", "middle");
text.SetAttribute("font-family", "Arial, sans-serif");
text.SetAttribute("font-size", "24");
text.SetAttribute("font-weight", "bold");
text.SetAttribute("fill", "#3e2723");
text.SetAttribute("style", "text-shadow: 2px 2px 4px rgba(0,0,0,0.3);");
text.AppendChild(document.CreateTextNode("SVG Style Demo"));
svgElement.AppendChild(text);
// Save the SVG document to file
document.Save(Path.Combine(OutputDir, "modify-style-using-dom.svg"));
}
// Normalize SVG color names, HEX values, and RGB values to HEX in C#
// Learn more: https://docs.aspose.com/svg/net/extract-svg-colors/
List<string> sourceColors = new List<string>
{
"red",
"#808080",
"rgb(128, 128, 128)"
};
// Convert each color value to HEX for easier comparison
foreach (string sourceColor in sourceColors)
{
Color color = Color.FromString(sourceColor);
Console.WriteLine($"{sourceColor} -> {color.ToRgbHexString()}");
}
// Normalize SVG color values to HEX format in C#
// Learn more: https://docs.aspose.com/svg/net/convert-color-codes/
// Store equivalent colors written in different formats
List<string> sourceColors = new List<string>
{
"#808080",
"rgb(128, 128, 128)",
"hsl(0, 0%, 50%)"
};
foreach (string sourceColor in sourceColors)
{
// Parse each color value from a string
Color color = Color.FromString(sourceColor);
// Convert each color to HEX and print the result
Console.WriteLine($"{sourceColor} -> {color.ToRgbHexString()}");
}
// Replace SVG colors in inline CSS style attributes in C#
// Learn more: https://docs.aspose.com/svg/net/replace-svg-colors/
// Load the source SVG file that contains inline style declarations
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
{
// Define the inline CSS color value to find and the new color value
string sourceColor = "grey";
string newColor = "#1976d2";
// Select only SVG elements that have a style attribute
foreach (Element element in document.QuerySelectorAll("[style]"))
{
string style = element.GetAttribute("style");
List<string> updatedDeclarations = new List<string>();
// Split the inline style into individual CSS declarations
foreach (string declaration in style.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
string[] parts = declaration.Split(':', 2);
if (parts.Length != 2)
{
// Keep malformed or nonstandard declarations unchanged
updatedDeclarations.Add(declaration.Trim());
continue;
}
string property = parts[0].Trim();
string value = parts[1].Trim();
// Replace only the CSS declaration value that matches the source color
if (value.Equals(sourceColor, StringComparison.OrdinalIgnoreCase))
{
value = newColor;
}
updatedDeclarations.Add($"{property}: {value}");
}
// Write the updated inline style back to the SVG element
element.SetAttribute("style", string.Join("; ", updatedDeclarations));
}
// Save the SVG file with replaced inline style colors
document.Save(Path.Combine(OutputDir, "replace-svg-colors-inline-style.svg"));
}
// Replace SVG fill, stroke, and gradient stop colors in C#
// Learn more: https://docs.aspose.com/svg/net/replace-svg-colors/
// Load the source SVG file that contains color attributes and gradient stops
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
{
// Define the SVG color to find and the replacement color to apply
string sourceColor = "grey";
string newColor = "#1976d2";
// Limit replacement to SVG attributes that commonly store visible colors
string[] colorAttributes = { "fill", "stroke", "stop-color" };
// Find all SVG elements and inspect their color-related attributes
foreach (Element element in document.QuerySelectorAll("*"))
{
foreach (string attributeName in colorAttributes)
{
string value = element.GetAttribute(attributeName);
if (!string.IsNullOrWhiteSpace(value) &&
value.Trim().Equals(sourceColor, StringComparison.OrdinalIgnoreCase))
{
// Replace only attributes whose value matches the source color
element.SetAttribute(attributeName, newColor);
}
}
}
// Save the SVG file with replaced attribute colors
document.Save(Path.Combine(OutputDir, "replace-svg-colors-attributes.svg"));
}
// Replace an SVG fill gradient reference with another gradient in C#
// Learn more: https://docs.aspose.com/svg/net/change-gradient-colors/
// Load an SVG file that uses a gradient as a fill paint server
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "linear-gradient.svg")))
{
string oldGradientRef = "url(#grad1)";
string newGradientRef = "url(#newBrandGradient)";
// Create a new gradient definition
const string SvgNamespace = "http://www.w3.org/2000/svg";
Element defs = document.QuerySelector("defs");
Element newGradient = document.CreateElementNS(SvgNamespace, "linearGradient");
newGradient.SetAttribute("id", "newBrandGradient");
newGradient.SetAttribute("x1", "0%");
newGradient.SetAttribute("y1", "0%");
newGradient.SetAttribute("x2", "100%");
newGradient.SetAttribute("y2", "0%");
// Add the first color stop to the new gradient
Element firstStop = document.CreateElementNS(SvgNamespace, "stop");
firstStop.SetAttribute("offset", "0%");
firstStop.SetAttribute("stop-color", "#1a237e");
// Add the second color stop to the new gradient
Element secondStop = document.CreateElementNS(SvgNamespace, "stop");
secondStop.SetAttribute("offset", "100%");
secondStop.SetAttribute("stop-color", "#26c6da");
newGradient.AppendChild(firstStop);
newGradient.AppendChild(secondStop);
defs.AppendChild(newGradient);
// Repoint shapes from the old gradient to the new gradient
foreach (Element element in document.QuerySelectorAll("[fill]"))
{
if (element.GetAttribute("fill").Trim() == oldGradientRef)
{
element.SetAttribute("fill", newGradientRef);
}
}
// Save the SVG file with the updated gradient reference
document.Save(Path.Combine(OutputDir, "gradient-fill-reference-updated.svg"));
}
// Replace stop colors in all SVG gradients using C#
// Learn more: https://docs.aspose.com/svg/net/change-gradient-colors/
// Load an SVG file that contains gradient stop colors
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "linear-gradient.svg")))
{
// Define the source stop colors and their replacements
Dictionary<string, string> palette = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["LIGHTSALMON"] = "#ff7043",
["TEAL"] = "#0277bd",
["LIGHTPINK"] = "#f06292"
};
// Select stops inside both linear and radial gradients
foreach (Element stop in document.QuerySelectorAll("linearGradient stop, radialGradient stop"))
{
string stopColor = stop.GetAttribute("stop-color");
// Replace stop-color written as an SVG attribute
if (!string.IsNullOrWhiteSpace(stopColor) &&
palette.TryGetValue(stopColor.Trim(), out string replacement))
{
stop.SetAttribute("stop-color", replacement);
}
string style = stop.GetAttribute("style");
if (string.IsNullOrWhiteSpace(style))
{
continue;
}
List<string> updatedDeclarations = new List<string>();
// Replace stop-color written inside an inline style declaration
foreach (string declaration in style.Split(';', StringSplitOptions.RemoveEmptyEntries))
{
string[] parts = declaration.Split(':', 2);
if (parts.Length != 2)
{
updatedDeclarations.Add(declaration.Trim());
continue;
}
string property = parts[0].Trim();
string value = parts[1].Trim();
if (property.Equals("stop-color", StringComparison.OrdinalIgnoreCase) &&
palette.TryGetValue(value, out replacement))
{
value = replacement;
}
updatedDeclarations.Add($"{property}: {value}");
}
stop.SetAttribute("style", string.Join("; ", updatedDeclarations));
}
// Save the SVG file after replacing gradient stop colors
document.Save(Path.Combine(OutputDir, "gradient-stops-replaced.svg"));
}
// Replace an SVG color palette in C#
// Learn more: https://docs.aspose.com/svg/net/replace-svg-colors/
// Load the source SVG file whose colors will be replaced as a palette
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "replace-svg-colors.svg")))
{
// Map each source SVG color to its replacement color
Dictionary<string, string> palette = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["grey"] = "#a02601",
["bisque"] = "#ffd1cf",
["silver"] = "#fa90a7"
};
// Search only SVG attributes that store visible paint colors
string[] colorAttributes = { "fill", "stroke", "stop-color" };
// Replace several known SVG colors with a new palette
foreach (Element element in document.QuerySelectorAll("*"))
{
foreach (string attributeName in colorAttributes)
{
string value = element.GetAttribute(attributeName);
if (!string.IsNullOrWhiteSpace(value) &&
palette.TryGetValue(value.Trim(), out string replacement))
{
// Apply the matching palette color to the current SVG attribute
element.SetAttribute(attributeName, replacement);
}
}
}
// Save the SVG file with the new color palette
document.Save(Path.Combine(OutputDir, "replace-svg-colors-palette.svg"));
}
// Save an edited SVG gradient and export it to PNG in C#
// Learn more: https://docs.aspose.com/svg/net/change-gradient-colors/
// Load an SVG file that contains a radial gradient
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "radial-gradient.svg")))
{
Element gradient = document.QuerySelector("radialGradient#myRG");
// Recolor selected radial gradient stops before saving and exporting
foreach (Element stop in gradient.QuerySelectorAll("stop"))
{
string offset = stop.GetAttribute("offset").Trim();
if (offset == "0%")
{
stop.SetAttribute("stop-color", "#fffde7");
}
else if (offset == "60%")
{
stop.SetAttribute("stop-color", "#283593");
}
}
string svgOutputPath = Path.Combine(OutputDir, "radial-gradient-edited.svg");
string pngOutputPath = Path.Combine(OutputDir, "radial-gradient-edited.png");
// Save the editable SVG result
document.Save(svgOutputPath);
// Export the edited SVG document to PNG
ImageSaveOptions options = new ImageSaveOptions();
Converter.ConvertSVG(document, options, pngOutputPath);
}
// Set SVG fill opacity and stroke opacity separately in C#
// Learn more: https://docs.aspose.com/svg/net/svg-opacity-and-transparent-colors/
// Load the source SVG file
using (SVGDocument document = new SVGDocument(Path.Combine(DataDir, "svg-opacity.svg")))
{
// Select a group with filled and stroked shapes
Element rings = document.QuerySelector("#rings");
// Make the fill more transparent while keeping the stroke easier to see
rings.SetAttribute("fill-opacity", "0.35");
rings.SetAttribute("stroke-opacity", "0.85");
// Save the SVG with separate fill and stroke opacity
document.Save(Path.Combine(OutputDir, "svg-fill-stroke-opacity.svg"));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment