Convert SVG in Python

Use Converter.convert_svg() with the save options for the required output. Aspose.HTML for Python via .NET converts SVG files, inline SVG strings, and SVGDocument objects to PDF, XPS, DOCX, JPG, PNG, BMP, TIFF, and GIF.

SVG is an XML-based vector format whose vector shapes, paths, and text can be scaled without losing sharpness. Converting SVG is useful when an application needs a printable document, a raster image, a thumbnail, or output for a workflow that does not accept SVG markup.

How SVG Conversion Works

  1. Prepare the SVG source as a file, an inline string, or an SVGDocument object.
  2. Create save options for the required output, such as PdfSaveOptions, XpsSaveOptions, DocSaveOptions, or ImageSaveOptions.
  3. Call Converter.convert_svg() with the SVG source, save options, and output path.

The following example converts an inline SVG circle to PNG. The parameterless ImageSaveOptions constructor uses PNG as the default image format.

 1# Convert SVG to PNG in Python from code
 2
 3import os
 4import aspose.html.converters as conv
 5import aspose.html.saving as sav
 6
 7# Prepare the output path
 8output_dir = "output"
 9if not os.path.exists(output_dir):
10    os.makedirs(output_dir)
11save_path = os.path.join(output_dir, "circle.png")
12
13# Define the SVG code
14svg_code = """<svg xmlns="http://www.w3.org/2000/svg">
15<circle cx="100" cy="100" r="60" fill="teal" stroke="salmon" stroke-width="10" />
16</svg>"""
17
18# Configure PNG output
19options = sav.ImageSaveOptions()
20
21# Convert SVG to PNG
22conv.Converter.convert_svg(svg_code, ".", options, save_path)

SVG Conversion Guides

OutputWhen to use itGuide
PDFCreate a fixed-layout document for sharing, printing, or archiving.Convert SVG to PDF
PNGCreate a lossless raster image that can preserve transparency.Convert SVG to PNG
JPG/JPEGCreate a widely supported compressed image when transparency is not required.Convert SVG to JPG

Other Supported SVG Outputs

Aspose.HTML also converts SVG to XPS, DOCX, BMP, GIF, and TIFF. Select the corresponding save options and use an output file extension that matches the selected format.

OutputSave optionsOutput extension
XPSXpsSaveOptions().xps
DOCXDocSaveOptions().docx
BMPImageSaveOptions(ImageFormat.BMP).bmp
GIFImageSaveOptions(ImageFormat.GIF).gif
TIFFImageSaveOptions(ImageFormat.TIFF).tiff or .tif

For raster formats, pass the configured ImageSaveOptions object to Converter.convert_svg(). Setting only the file extension does not select the output image format; the ImageFormat value and extension should correspond.

Related SVG Workflows

Other Platforms

Try Online SVG Conversion

                
            

Use the free online SVG Converter for quick manual conversion. Use Aspose.HTML for Python via .NET when SVG conversion must run programmatically in a Python application.