Skip to content

Instantly share code, notes, and snippets.

@pedroarthur
Created October 5, 2016 01:22
Show Gist options
  • Save pedroarthur/3960cc817903ab16a59b702bc711291c to your computer and use it in GitHub Desktop.
Save pedroarthur/3960cc817903ab16a59b702bc711291c to your computer and use it in GitHub Desktop.
Parse a SVG file and creates few others that display a layer at a time (eg, to use with LaTeX xmpmulti's multiinclude)
from xml.dom.minidom import parse as parse_xml_from_file
from sys import argv, exit
# SVG file name (drawing.svg)
input_file = argv[1]
# Output files prefix (animation/steps)
output_prefix = argv[2]
# one or more layers suffixes
layers_suffixes = argv[3:]
# Example:
#
# python layer-display-toggle.py drawing.svg animation/step l1 l2 l3
#
# will filter all layers in drawing.svg that starts with llf: (aka layer label filter) and
# export all layers that ends with l1, l2 and l3 in three different files. So, if you file
# has layers llf:al1, llf:bl1, llf:l2, llf:l3, the following files will be created:
#
# animation/step-0.svg
# animation/step-1.svg
# animation/step-3.svg
#
# Be sure that animation folder exists.
if len(layers_suffixes) == 0:
raise Exception, "empty layers spec"
layer_label_filter = lambda e: e.getAttribute("inkscape:label").startswith("llf:")
with open(input_file) as doc:
dom = parse_xml_from_file(doc)
layers = filter(layer_label_filter, dom.getElementsByTagName("g"))
results = [ ]
for idx, candidate in enumerate(layers_suffixes):
found = False
for layer in layers:
if layer.getAttribute("inkscape:label").endswith(candidate):
found = True
layer.setAttribute("style", "display:inline")
else:
layer.setAttribute("style", "display:none")
if not found:
raise Exception, "{} layer not found".format(candidate)
results.append((idx, dom.toprettyxml()))
for idx, data in results:
with open("{}-{}.svg".format(output_prefix, idx), 'a') as output_file:
output_file.write(data)
exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment