Last active
January 28, 2024 07:08
-
-
Save ajmaradiaga/7d0d5a7a528db46f08b810d575d15916 to your computer and use it in GitHub Desktop.
The Python script process the Draw.io library files and "extract" the images from within it. In my case, I want to save the images as SVG and PNG files.
This file contains 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 base64 | |
import json | |
import xml.etree.ElementTree as ET | |
import os | |
import cairosvg | |
process_files = [ | |
'Library-1.drawio', | |
'Library-2.drawio' | |
] | |
for file in process_files: | |
file_name = os.path.basename(file) | |
directory_name = file_name.replace(".drawio", "") | |
# Parse the XML file and get the mxlibrary node | |
tree = ET.parse(file) | |
root = tree.getroot() | |
if root.tag != "mxlibrary": | |
print(f"Error: {file} is not a valid mxlibrary file") | |
continue | |
# Extract the JSON array from the mxlibrary node | |
json_array = json.loads(root.text) | |
# Create the directories where the output images will be saved | |
os.makedirs(f"{directory_name}/svg", exist_ok=True) | |
os.makedirs(f"{directory_name}/png", exist_ok=True) | |
# Iterate through every item in the JSON array | |
for item in json_array: | |
if "data" in item and "title" in item: | |
# Extract the data and title from the item | |
data = item["data"] | |
title = item["title"] | |
if "data:image/svg+xml;base64," in data: | |
# Extract the base64 encoded SVG data | |
svg_data = data.replace("data:image/svg+xml;base64,", "") | |
# Decode the base64 encoded SVG data | |
svg_bytes = base64.b64decode(svg_data) | |
# Convert the SVG bytes to a string | |
svg_string = svg_bytes.decode("utf-8") | |
try: | |
# Save the SVG to a file | |
cairosvg.svg2svg(bytestring=svg_string, write_to=f"{directory_name}/svg/{title}.svg") | |
# Convert the SVG to PNG | |
cairosvg.svg2png(bytestring=svg_string, write_to=f"{directory_name}/png/{title}.png") | |
except Exception as e: | |
print(f"Error converting {title} to PNG: {e}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment