Extract Inline and External SVG from HTML in Java
Aspose.HTML for Java
loads a web page into an HTMLDocument so an application can inspect both embedded SVG markup and linked SVG resources. Inline graphics appear as <svg> elements in the DOM, while external SVG files can be referenced by elements such as <img src="image.svg">.
Save an inline graphic by writing its getOuterHTML() value to an .svg file. For an external graphic, resolve its relative URL against document.getBaseURI(), request the resource through the document network service, and save the returned bytes without re-encoding them.
Save SVG Graphics Found on a Web Page
The Java example saves every inline <svg> element and downloads distinct external SVG files referenced by <img> elements. Separate names make the two source types easy to identify in the svg output directory.
Extract SVG from Website in Java
Path outputDirectory = Paths.get("svg");
Files.createDirectories(outputDirectory);
try (HTMLDocument document = new HTMLDocument("https://products.aspose.com/html/java/")) {
// Save inline SVG elements as standalone files
HTMLCollection inlineSvgElements = document.getElementsByTagName("svg");
int inlineNumber = 1;
for (Element svgElement : inlineSvgElements) {
Path outputPath = outputDirectory.resolve("inline-" + inlineNumber + ".svg");
byte[] svgMarkup = svgElement.getOuterHTML().getBytes(StandardCharsets.UTF_8);
Files.write(outputPath, svgMarkup);
inlineNumber++;
}
// Collect distinct external SVG sources from image elements
HTMLCollection images = document.getElementsByTagName("img");
Set<String> externalSources = new LinkedHashSet<>();
for (Element image : images) {
String source = image.getAttribute("src");
if (source.isEmpty()) {
continue;
}
Url resourceUrl = new Url(source, document.getBaseURI());
if (resourceUrl.getPathname().toLowerCase().endsWith(".svg")) {
externalSources.add(source);
}
}
int externalNumber = 1;
for (String source : externalSources) {
Url resourceUrl = new Url(source, document.getBaseURI());
RequestMessage request = new RequestMessage(resourceUrl);
ResponseMessage response = document.getContext().getNetwork().send(request);
if (response.isSuccess()) {
Path outputPath = outputDirectory.resolve("external-" + externalNumber + ".svg");
Files.write(outputPath, response.getContent().readAsByteArray());
externalNumber++;
}
}
}
SVG Extraction Steps in Java
- Load the target page with
HTMLDocument. - Collect inline
<svg>elements withgetElementsByTagName("svg")and write each element’sgetOuterHTML()value as UTF-8 text. - Collect
<img>elements and read their nonemptysrcattributes. - Resolve every relative source with
Urland keep URLs whose path ends in.svg. - Send a
RequestMessagefor each external SVG and verify theResponseMessage. - Save every successful response as an
.svgfile withFiles.write().
Inline SVG vs External SVG
An inline SVG is part of the HTML DOM. Its XML markup is available through the corresponding <svg> element and can be serialized with getOuterHTML().
An external SVG is a separate resource referenced by a URL. The code downloads files used by <img> elements; SVG referenced through other elements, CSS, or fragment links requires selectors appropriate to those locations.
Read Extract SVG From Website in Java for the documented inline and external SVG workflows.
SVG Extraction Considerations
- Keep inline and external SVG separate. Inline SVG is serialized from the DOM, while an external SVG is downloaded as a resource response.
- Use unique output names. Multiple inline graphics have no original file name, and different external URLs can share the same final path segment.
- Check every resource response. An external URL can return an error page, an authentication response, or unavailable content instead of SVG data.
- Plan for large collections.
readAsByteArray()buffers each external SVG response in memory. Use a streaming strategy when a page can reference unusually large files or many resources. - Validate untrusted content. Treat downloaded SVG as active XML-based content and review scripts, links, and external references before publishing or displaying it.
- Respect copyright and website terms. Extract and reuse only SVG graphics that you own or are authorized to access. Public availability does not grant permission to redistribute protected logos, icons, or illustrations.
FAQ
1. Why can’t some SVG images be downloaded directly from a website?
Many websites embed graphics as inline <svg> elements instead of linking to separate .svg files. An inline SVG must be located in the HTML DOM and saved from its getOuterHTML() markup rather than downloaded from a resource URL.
2. How can I extract SVG files and icons from a web page in Java?
Aspose.HTML for Java can inspect the SVG sources present in a loaded document, but no single selector covers every placement. Check inline <svg>, <img src>, <object data>, <embed src>, CSS url(), and SVG sprite references according to how the page includes its graphics.
3. Does extracting SVG from HTML preserve vector quality?
Saving inline SVG markup or the original bytes of an external SVG does not rasterize the graphic, so its vector paths and scalable dimensions remain intact. The saved file can still render differently if it depends on page CSS, fonts, images, scripts, or external symbols that were not copied.
4. Can Aspose.HTML for Java extract SVG files from an entire website?
Aspose.HTML for Java extracts SVG from the page loaded into an HTMLDocument; it does not automatically crawl every page in a domain. To process an entire website, enumerate the permitted page URLs, inspect each document, and deduplicate the collected SVG resources.
Install Aspose.HTML for Java
Add Aspose.HTML for Java from the official Aspose repository. Replace ASPOSE_HTML_VERSION with an exact version from the
Aspose.HTML for Java releases
page, then reload or rebuild the project so the dependency is resolved.
Add the repository and dependency to the Maven project:
Maven – pom.xml
<repositories>
<repository>
<id>AsposeJavaAPI</id>
<url>https://releases.aspose.com/java/repo/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-html</artifactId>
<version>ASPOSE_HTML_VERSION</version>
</dependency>
</dependencies>Add the repository and dependency to the Gradle project:
Gradle – build.gradle
repositories {
maven {
url = uri('https://releases.aspose.com/java/repo/')
}
}
dependencies {
implementation 'com.aspose:aspose-html:ASPOSE_HTML_VERSION'
}Use a JDK compatible with the selected release. For manual JAR installation, Kotlin DSL, updates, and dependency troubleshooting, see Install Aspose.HTML for Java .
Related Java SVG and Extraction Tasks
Continue with image extraction, the Java data extraction hub, or SVG conversion examples.