Skip to content

Instantly share code, notes, and snippets.

@zengxs
Created September 12, 2023 09:00
Show Gist options
  • Save zengxs/1163f51444c3bc372f83f96eabe401e1 to your computer and use it in GitHub Desktop.
Save zengxs/1163f51444c3bc372f83f96eabe401e1 to your computer and use it in GitHub Desktop.
Convert SVG to Axure-compatible SVG using AppleScript and Pixelmator Pro.
#!/usr/bin/env python3
"""
Convert SVG to Axure-compatible SVG using AppleScript and Pixelmator Pro.
Axure convert optimized SVG to Shape will cause the SVG to be rendered deformed.
This script uses Pixelmator Pro to convert SVG to pixel-based SVG, which Axure
will convert to Shape correctly.
"""
import argparse
import sys
from pathlib import Path
from subprocess import PIPE, Popen
APPLE_SCRIPT = """
on run argv
set svg_file to POSIX file (item 1 of argv)
set out_file to POSIX file (item 2 of argv)
tell application "Pixelmator Pro"
activate
open svg_file
tell its front document
convert into pixels every layer
export to out_file as SVG
close saving no
end tell
end tell
end run
"""
def main():
if sys.platform != "darwin":
print("This script only works on macOS.", file=sys.stderr)
sys.exit(1)
parser = argparse.ArgumentParser()
parser.add_argument("input", help="SVG file/folder to convert")
args = parser.parse_args()
input_path = Path(args.input)
if not input_path.exists():
print(f"Input path does not exist: {input_path}", file=sys.stderr)
sys.exit(1)
elif input_path.is_file() and input_path.suffix != ".svg":
print(f"Input file is not an SVG: {input_path}", file=sys.stderr)
sys.exit(1)
if input_path.is_file():
convert_svg(input_path)
if input_path.is_dir():
if prompt_confirmation(f"Convert all SVG files in folder: {input_path}?"):
for svg_file in input_path.rglob("*.svg"):
convert_svg(svg_file)
else:
print("Cancelled.")
def prompt_confirmation(message):
"""Prompt user for confirmation."""
while True:
response = input(f"{message} [y/n]: ").lower()
if response in ["y", "yes"]:
return True
elif response in ["n", "no"]:
return False
else:
print("Invalid response. Please enter 'y' or 'n'.")
def convert_svg(svg_file):
"""Convert SVG to PNG using Pixelmator Pro."""
svg_file = Path(svg_file).absolute()
out_file = Path(svg_file).with_name(f"{svg_file.stem}-axure.svg").absolute()
if str(svg_file).endswith("-axure.svg"):
return
p = Popen(
["osascript", "-"] + [str(svg_file), str(out_file)],
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
encoding="utf8",
)
stdout, stderr = p.communicate(APPLE_SCRIPT)
if p.returncode != 0:
raise RuntimeError(stderr)
print(f"Converted SVG to File: {out_file}")
return stdout
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment