Extract SVG from a Website in Java

SVG graphics can appear in an HTML document as inline <svg> markup or as an external file referenced by a URL. Extracting inline SVG means saving the element markup, while extracting an external SVG requires resolving and downloading its resource URL.

To extract SVG from a website in Java, load the page into an HTMLDocument. Save the OuterHTML of each inline <svg> element, and separately locate external SVG references, resolve relative URLs against document.getBaseURI(), and download the resulting resources.

Extract Inline SVG from HTML

An inline SVG is represented by an <svg> element whose markup is part of the HTML document. It does not necessarily have a separate image URL, so saving the element’s serialized markup creates the local SVG file.

The example uses getOuterHTML() from the Element API to preserve each complete <svg> element, including its root tag and attributes.

  1. Create an HTMLDocument from the source web page URL.
  2. Call getElementsByTagName(“svg”) to collect inline SVG elements.
  3. Iterate through the returned collection.
  4. Read each element’s getOuterHTML() value and write it to a uniquely named .svg file.
 1// How to extract inline SVG images from a webpage using Java
 2
 3// Open a document you want to download inline SVG images from
 4final 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.getLength(); i++) {
10    // Save every image to a local file system
11    FileHelper.writeAllText("{i}.svg", images.get_Item(i).getOuterHTML());
12}

Generate each output name explicitly. Java does not interpolate {i} inside an ordinary string literal; use an expression such as i + ".svg" to create a different name for each inline SVG.

Always respect the website’s terms of use, copyright, and permissions when downloading or reusing SVG graphics.

Download External SVG Files

An external SVG is stored separately from the HTML document and referenced by a URL. The current example examines <img src> values and keeps references whose strings end with .svg.

This is a deliberately narrow detection rule. External SVG can also be referenced by <object>, <embed>, <source>, <use>, CSS, or a URL whose pathname does not expose the .svg extension.

  1. Load the source web page into an HTMLDocument.
  2. Collect <img> elements and read distinct, non-empty src values.
  3. Identify SVG references and resolve relative values with the Url class and document.getBaseURI().
  4. Create and send a RequestMessage for each absolute SVG URL.
  5. Check the ResponseMessage and save its bytes to a uniquely named local file.
 1// Download external SVG images from HTML using Java
 2
 3// Open a document you want to download external SVGs from
 4final 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
10java.util.Set<String> urls = new HashSet<>();
11for (Element element : images) {
12    urls.add(element.getAttribute("src"));
13}
14
15// Filter out non SVG images
16java.util.List<String> svgUrls = new ArrayList<>();
17for (String url : urls) {
18    if (url.endsWith(".svg")) {
19        svgUrls.add(url);
20    }
21}
22// Create absolute SVG image URLs
23java.util.List<Url> absUrls = svgUrls.stream()
24        .map(src -> new Url(src, document.getBaseURI()))
25        .collect(Collectors.toList());
26
27// foreach to while statements conversion
28for (Url url : absUrls) {
29    // Create a downloading request
30    final RequestMessage request = new RequestMessage(url);
31
32    // Download SVG image
33    final ResponseMessage response = document.getContext().getNetwork().send(request);
34
35    // Check whether response is successful
36    if (response.isSuccess()) {
37        String[] split = url.getPathname().split("/");
38        String path = split[split.length - 1];
39
40        // Save file to a local file system
41        FileHelper.writeAllBytes(path, response.getContent().readAsByteArray());
42    }
43}

The endsWith(".svg") check is case-sensitive and does not match a URL followed by a query string or fragment. For more reliable detection, inspect the resolved URL pathname and validate the response content type.

SVG Sources Covered by the Examples

SVG sourceCovered?Notes
Inline <svg> elementYesThe complete element markup is saved with getOuterHTML().
<img src="image.svg">YesThe string must end with lowercase .svg in the current example.
<object data="image.svg"> or <embed src="image.svg">NoThese elements require separate attribute queries.
SVG sprite referenced by <use href>NoThe reference may identify a symbol inside another SVG resource.
CSS background-imageNoThe URL is stored in CSS rather than an HTML image attribute.
Extensionless SVG URLNoDetection requires response metadata or content inspection.

Common SVG Extraction Issues

IssueLikely causeFix
Repeated extraction overwrites the same inline SVG fileThe output name is a constant string.Build the file name from the loop index or another unique value.
An external SVG with query parameters is skippedIts URL does not end with .svg.Test the normalized URL pathname rather than the complete URL string.
A saved inline SVG looks different outside the pageIts styles, referenced symbols, fonts, or other dependencies are defined outside the <svg> element.Preserve or inline the required dependencies before using the file independently.
An empty src resolves to the web page URLEmpty attribute values were not removed before URL resolution.Skip null, empty, and whitespace-only values.
Two downloaded SVGs overwrite each otherTheir URLs have the same final path segment.Generate unique destination names.

FAQ

Why can an inline SVG not be downloaded by its image URL?

An inline SVG is part of the HTML markup and may not have a separate resource URL. Extract its <svg> element and save the serialized markup instead.

Does the example extract individual symbols from an SVG sprite?

No. The inline example saves complete <svg> elements, while the external example downloads complete SVG files referenced through <img src>. Extracting an individual <symbol> referenced by <use> requires additional DOM and reference-processing logic.

Related Aspose.HTML Articles

Other Platforms

Try HTML Web Applications

Aspose.HTML provides free online HTML Web Applications for converting files, extracting web data, generating HTML, and analyzing pages without installing additional software.

Text “HTML Web Applications”