Create SVG File, Load and Read SVG in Python

How to Create SVG File

This article explains the fundamental SVGDocument workflows used as a starting point for all SVG processing tasks.

Aspose.SVG for Python via .NET provides the SVGDocument class, the entry point for creating, loading, and reading SVG content. The SVGDocument serves as the root of the SVG DOM hierarchy, holding the entire content and adhering to W3C SVG 2.0 and WHATWG DOM specifications.

The SVGDocument class supports multiple constructors, allowing you to:

To continue following this tutorial, you should install and configure Aspose.SVG for Python via .NET library in your Python project. Our code examples help you to create, load, and read SVG files using the Python library.

Create an Empty SVG Document

An empty document is useful as a canvas for building SVG elements programmatically. The following Python code snippet shows the usage of the default SVGDocument() constructor to create an SVG document.

If you want to save created empty SVG document to a file, use the following Python code snippet:

1from aspose.svg import SVGDocument
2
3# Create a new SVG document
4document = SVGDocument()
5
6# Save the empty SVG document
7document.save("empty-document.svg")

Below is an example code snippet that demonstrates how to create an empty SVG document and save it to a file in the specified output directory. The example shows how you can set attributes such as width and height for the root <svg> element:

 1import os
 2from aspose.svg import SVGDocument
 3
 4# Set up the output directory
 5output_folder = "output/"
 6if not os.path.exists(output_folder):
 7    os.makedirs(output_folder)
 8
 9# Create a new empty SVG document
10document = SVGDocument()
11
12# Optionally, you can add attributes to the root <svg> element
13svg_element = document.document_element
14svg_element.set_attribute("width", "100%")
15svg_element.set_attribute("height", "100%")
16
17# Define the output file path
18output_file = os.path.join(output_folder, "create-empty.svg")
19
20# Save the SVG document to a file
21document.save(output_file)
22
23print(f"Empty SVG document saved to {output_file}")

More details about SVG file saving are in the Save SVG File article. In the article Navigate SVG, You learn how to use the Aspose.SVG Python library to perform a detailed inspection of the SVG document and its elements and how to navigate the SVG document using CSS Selector or XPath.

Create SVG from a Memory String

You can create SVG from a string content using SVGDocument(content, base_uri) constructor. If your case is to produce a document from a user string directly in your code and you don’t need to save it to a file, the following example could help you: we produce an SVG document that contains a color-filled circle with a radius of 50 pixels and colored stroke.

 1from aspose.svg import SVGDocument
 2
 3documentContent = "<svg xmlns='http://www.w3.org/2000/svg'><circle cx='100' cy='150' r='50' stroke='#2F4F4F' stroke-width='4' fill='#FF7F50' /></svg>"
 4
 5# Create a new SVG document
 6document = SVGDocument(documentContent, ".")
 7svg_element = document.document_element
 8
 9# Work with the document here...
10
11# Save the document
12document.save("create-svg-from-string.svg")

Load SVG from a File

To load SVG from a file, use one of the constructors of the SVGDocument class and pass the file path as the input parameter to it.

1from aspose.svg import SVGDocument
2
3#  Load an SVG file located on disk
4document = SVGDocument("document.svg")
5
6#  Work with the SVG document here...
7
8# Save the document
9document.save("load-svg-from-file.svg")

Load SVG from a URL

Loading from remote URLs requires network access and may fail in restricted or offline environments. The following Python code example could help you to create a document from a URL referring to the SVG file:

1from aspose.svg import SVGDocument
2
3# Load SVG from a URL
4document = SVGDocument("https://docs.aspose.com/svg/files/owl.svg")
5
6#  Work with the SVG document here...
7
8# Save the document
9document.save("load-svg-from-url.svg")

Common Mistakes and Fixes

ProblemCauseSolution
Saved SVG appears blank when openedThe document contains no visible graphical elements or the SVG viewport size is undefined.Ensure drawable elements are added and define width, height, or a viewBox attribute for the root <svg> element.
Relative resources (images, fonts, styles) are not loadedThe base URI is missing or incorrect when creating an SVG from a string.Provide a valid base URI when using SVGDocument(content, base_uri) so relative paths can be resolved correctly.
File not found error when loading SVGRelative paths are resolved against the application’s current working directory.Use absolute file paths or verify the working directory using os.getcwd() before loading the file.
Unexpected namespace prefixes appear in the saved SVGElements were created or imported with explicit XML namespaces different from the default SVG namespace.Create elements using the standard SVG namespace (http://www.w3.org/2000/svg) and avoid mixing nodes from incompatible XML documents.

FAQ

Q1: Can I modify an SVG loaded from a URL without downloading it manually? A: Yes. When you pass a URL to the SVGDocument constructor, the library loads the SVG content into memory automatically. You can then modify the document and save it locally.

Q2: Does the SVGDocument constructor automatically create the root <svg> element? A: Yes. The default SVGDocument() constructor creates a valid SVG document with a root <svg> element accessible via document.document_element.

Q3: Do I need to explicitly close an SVGDocument after saving? A: No. Explicit closing is not required. System resources are released automatically when the SVGDocument object goes out of scope and is garbage-collected.

Q4: Why should I specify a base URI when creating SVG from a string? A: The base URI defines how relative resources such as images, stylesheets, or fonts referenced inside the SVG are resolved. Without it, external resources may fail to load correctly.

Q5: How can I embed external images directly into an SVG file? A: A base URI only helps resolve resource paths. To embed images directly into an SVG, convert them to Base64 data URIs and assign them to the corresponding image attributes.

Conclusion

Aspose.SVG for Python via .NET makes creating, loading, and reading SVG files simple and reliable. By leveraging the versatile SVGDocument constructors, you can work with blank canvases, in‑memory markup, local files, or remote resources – all while staying compliant with the latest SVG standards.

Related Articles

Close
Loading

Analyzing your prompt, please hold on...

An error occurred while retrieving the results. Please refresh the page and try again.

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.