Extract SVG From Website Using C#

To extract SVG from a website in C#, load the page with HTMLDocument, save inline <svg> elements with OuterHTML, and find external SVG URLs in image elements. Resolve relative URLs with BaseURI, send requests through Context.Network, and save successful SVG responses locally.

SVG is a vector graphics format designed primarily for the web, often used in HTML documents. The main advantage of SVG is its ability to scale to any size without losing quality. Along with programmability, small file size, styling, and interactivity, SVG can improve web pages’ visual appeal and functionality. Designers and developers may need to extract SVG images from a website for archiving, analysis, migration, or personal design research.

Downloading SVG is not always as easy as it seems. If you have tried to save an image from a web page with right-click, you may have noticed that SVG files are often difficult to extract. Some SVG graphics are embedded directly in HTML as <svg> elements, while others are loaded as external files. Aspose.HTML for .NET lets you handle both cases programmatically.

Extract Inline SVG from Website in C#

Inline SVG images are SVG elements <svg> whose content describes the image. Inline SVG refers to embedding SVG code directly into HTML code rather than linking to an external SVG file. This is a popular technique for creating website icons, logos, and other graphical elements.

To save inline SVG images, we will find all <svg> elements in an HTML document and use the OuterHTML property to get their content. To download inline SVG from a website in C#:

  1. Use the HTMLDocument(Url) constructor to create an instance of the HTMLDocument class and pass it the URL of the website from which you want to extract inline SVG images.
  2. Use the GetElementsByTagName(“svg”) method to collect all <svg> elements. The method returns a list of the HTML document’s <svg> elements.
  3. Create a loop to iterate through each SVG image in the images array.
  4. For each image in the array, use the OuterHTML property to get the SVG element content and the File.WriteAllText() method, which writes the SVG content to a local file.
 1// How to extract inline SVG images from a webpage using C#
 2
 3// Open a document you want to download inline SVG images from
 4using HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/net/");
 5
 6// Collect all inline SVG images
 7HTMLCollection images = document.GetElementsByTagName("svg");
 8
 9for (int i = 0; i < images.Length; i++)
10{
11    // Save each SVG element as an individual .svg file
12    File.WriteAllText(Path.Combine(OutputDir, $"{i}.svg"), images[i].OuterHTML);
13}

Note: Some SVG files may be protected by copyright, so check the terms of use before extracting and using them. For example, using a company logo or other extracted SVG files in your design projects might be considered plagiarism. Ask the website owner for permission before you reuse their files.

Extract External SVG from Website in C#

External SVG is an SVG file stored outside an HTML document and loaded into the document using, for example, a <img> tag. Separating SVG files from HTML makes it possible to reuse the same SVG image in multiple places without duplicating the code, making web pages more efficient and easier to maintain.

External SVG images are represented by the <img> element, which in turn can also refer to other types of images, so SVG images should be further filtered. Let’s look at how to download SVG from a website using the Aspose.HTML for .NET library:

  1. Use the HTMLDocument(Url) constructor to create an instance of the HTMLDocument class and pass it the URL of the website from which you want to extract external SVGs.
  2. Use the GetElementsByTagName(“img”) method to collect all <img> elements. The method returns a list of the HTML document’s <img> elements.
  3. Use the Select() method to create a distinct collection of relative image URLs and the GetAttribute(“src”) method to extract the src attribute of each <img> element.
  4. To filter out non-SVG images, use the Where() and the EndsWith() methods to check if the URL ends with the .svg extension.
  5. Create absolute SVG image URLs using the Url class and the BaseURI property of the HTMLDocument class.
  6. Then, for each absolute URL, create a request using the RequestMessage class.
  7. Use the document’s Context.Network.Send(request) method to send the request. The response is checked to ensure it was successful.
  8. Finally, if the response was successful, use the File.WriteAllBytes() method to save SVG to a local file.
 1// Download external SVG images from HTML using C#
 2
 3// Open a document you want to download external SVGs from
 4using HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/net/");
 5
 6// Collect all image elements
 7HTMLCollection images = document.GetElementsByTagName("img");
 8
 9// Create a distinct collection of relative image URLs
10IEnumerable<string> urls = images.Select(element => element.GetAttribute("src")).Distinct();
11
12// Filter out non SVG images
13IEnumerable<string> svgUrls = urls.Where(url => url.EndsWith(".svg"));
14
15// Create absolute SVG image URLs
16IEnumerable<Url> absUrls = svgUrls.Select(src => new Url(src, document.BaseURI));
17
18foreach (Url url in absUrls)
19{
20    // Create a downloading request
21    using RequestMessage request = new RequestMessage(url);
22
23    // Download SVG image
24    using ResponseMessage response = document.Context.Network.Send(request);
25
26    // Check whether response is successful
27    if (response.IsSuccess)
28    {
29        // Save SVG image to a local file system
30        File.WriteAllBytes(Path.Combine(OutputDir, url.Pathname.Split('/').Last()), response.Content.ReadAsByteArray());
31    }
32}

Common SVG Extraction Issues

ProblemCauseSolution
Inline SVG is saved without expected stylingThe SVG depends on CSS rules outside the <svg> element.Inspect related styles and include required CSS when the standalone SVG must preserve the original appearance.
External SVG files are missedThe page references SVG through CSS, <object>, <embed>, or a URL that does not end with .svg.Check additional elements and attributes when the page does not use <img src="...svg">.
Relative SVG URLs resolve incorrectlyThe source URL is combined without the page base URI.Resolve SVG links with the document BaseURI before sending requests.
SVG download fails with 403 or 404The server blocks direct resource requests or the URL is redirected.Check response status, redirects, headers, and permissions before saving the file.
Extracted SVG should not be reused commerciallySVGs can be copyrighted logos, icons, or illustrations.Check the website terms and obtain permission before reuse.

FAQ

What is the difference between inline and external SVG?

Inline SVG is stored directly in the HTML document inside an <svg> element. External SVG is stored in a separate .svg file and referenced from the page, often through an <img> element.

How do I save inline SVG?

Find <svg> elements in the loaded document and save each element’s OuterHTML to a local .svg file.

How do I download external SVG files?

Find SVG resource URLs, resolve them against the document base URI, send requests with the network API, and save successful responses to local files.

Can all SVG files from a page be found through `` tags?

No. Some pages reference SVG through CSS, <object>, <embed>, scripts, or icon links. The examples focus on inline SVG and external SVG referenced by image elements.

Other Platforms

Related Data Extraction Articles

The complete C# examples and data files are available in the Aspose.HTML for .NET GitHub repository.