exportlayers.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python2
  2. """
  3. Export selected layers from Inkscape SVG.
  4. """
  5. from xml.dom import minidom
  6. import codecs
  7. def export_layers(src, dest, hide, show):
  8. """
  9. Export selected layers of SVG in the file `src` to the file `dest`.
  10. :arg str src: path of the source SVG file.
  11. :arg str dest: path to export SVG file.
  12. :arg list hide: layers to hide. each element is a string.
  13. :arg list show: layers to show. each element is a string.
  14. """
  15. svg = minidom.parse(open(src))
  16. g_hide = []
  17. g_show = []
  18. for g in svg.getElementsByTagName("g"):
  19. if g.attributes.has_key("inkscape:label"):
  20. label = g.attributes["inkscape:label"].value
  21. if label in hide:
  22. g.attributes['style'] = 'display:none'
  23. g_hide.append(g)
  24. elif label in show:
  25. g.attributes['style'] = 'display:inline'
  26. g_show.append(g)
  27. export = svg.toxml()
  28. codecs.open(dest, "w", encoding="utf8").write(export)
  29. print "Hide {0} node(s); Show {1} node(s).".format(
  30. len(g_hide), len(g_show))
  31. def main():
  32. from argparse import ArgumentParser
  33. parser = ArgumentParser(description=__doc__)
  34. parser.add_argument(
  35. '--hide', action='append', default=[],
  36. help='layer to hide. this option can be specified multiple times.')
  37. parser.add_argument(
  38. '--show', action='append', default=[],
  39. help='layer to show. this option can be specified multiple times.')
  40. parser.add_argument('src', help='source SVG file.')
  41. parser.add_argument('dest', help='path to export SVG file.')
  42. args = parser.parse_args()
  43. export_layers(**vars(args))
  44. if __name__ == '__main__':
  45. main()