Created
October 1, 2025 12:14
-
-
Save aspose-com-gists/51a77045d3be67bb4d973f3adb847447 to your computer and use it in GitHub Desktop.
Convert SVG to PNG in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import aspose.cad as cad | |
from aspose.cad.imageoptions import PngOptions | |
# A class to handle CAD image conversion using Aspose.CAD for Python via .NET | |
class CadImageConverter: | |
def __init__(self, input_path, output_path, license_path): | |
# Store input, output, and license file paths | |
self.input_path = input_path | |
self.output_path = output_path | |
self.license_path = license_path | |
self.image = None | |
self.raster_options = None | |
def apply_license(self): | |
# Apply the Aspose.CAD license to unlock full functionality | |
print("Applying Aspose.CAD license...") | |
license_obj = cad.License() | |
license_obj.set_license(self.license_path) | |
print("License applied successfully.") | |
def load_cad_image(self): | |
# Load a CAD (or SVG) file from the given input path | |
print(f"Loading CAD image froms: {self.input_path}") | |
self.image = cad.Image.load(self.input_path) | |
print("Image loaded successfully.") | |
def configure_rasterization(self, width=800.5, height=800.5, zoom=0.5, layers="Layer"): | |
# Configure rasterization options for converting vector to raster | |
print("Configuring rasterization options...") | |
self.raster_options = cad.imageoptions.CadRasterizationOptions() | |
# Set output image width | |
self.raster_options.page_width = width | |
# Set output image height | |
self.raster_options.page_height = height | |
# Define zoom level | |
self.raster_options.zoom = zoom | |
# Specify which layers to render | |
self.raster_options.layers = layers | |
print("Rasterization configured.") | |
def save_as_png(self): | |
# Save the loaded CAD image as a PNG using the configured rasterization | |
print(f"Saving image as PNG to: {self.output_path}") | |
png_options = PngOptions() | |
png_options.vector_rasterization_options = self.raster_options | |
self.image.save(self.output_path, png_options) | |
print("Image saved as PNG successfully.") | |
def main(): | |
input_svg = "sample1.svg" | |
output_png = "result-file.png" | |
license_file = "license.lic" | |
# Initialize converter with file paths | |
converter = CadImageConverter(input_svg, output_png, license_file) | |
# Apply license, load the image, configure rasterization, and save as PNG | |
converter.apply_license() | |
converter.load_cad_image() | |
converter.configure_rasterization() | |
converter.save_as_png() | |
# Run the script if executed directly. | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment