strokenostrokewidth.py 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. # usage:
  2. # strokenostrokewidth.py -d [svg folder] -f yes/no
  3. # looks for stroke attribute with no stroke-width attribute; if -f is "yes" then set stroke-width to 1
  4. import getopt, sys, os, os.path, re, xml.dom.minidom, xml.dom
  5. def usage():
  6. print """
  7. usage:
  8. strokenostrokewidth.py -d [svg folder] -f yes
  9. looks for stroke attribute with no stroke-width attribute; if -f is "yes" then set stroke-width to 1
  10. """
  11. def main():
  12. try:
  13. opts, args = getopt.getopt(sys.argv[1:], "hf:d:", ["help", "fix", "directory"])
  14. except getopt.GetoptError, err:
  15. # print help information and exit:
  16. print str(err) # will print something like "option -a not recognized"
  17. usage()
  18. sys.exit(2)
  19. dir = None
  20. fix = None
  21. for o, a in opts:
  22. #print o
  23. #print a
  24. if o in ("-d", "--directory"):
  25. dir = a
  26. elif o in ("-h", "--help"):
  27. usage()
  28. sys.exit(2)
  29. elif o in ("-f", "--fix"):
  30. fix = a
  31. else:
  32. assert False, "unhandled option"
  33. if(not(dir)):
  34. usage()
  35. sys.exit(2)
  36. for root, dirs, files in os.walk(dir, topdown=False):
  37. for filename in files:
  38. if not filename.endswith(".svg"):
  39. continue
  40. svgFilename = os.path.join(root, filename)
  41. try:
  42. dom = xml.dom.minidom.parse(svgFilename)
  43. except xml.parsers.expat.ExpatError, err:
  44. print str(err), svgFilename
  45. continue
  46. changed = 0
  47. todo = [dom.documentElement]
  48. while len(todo) > 0:
  49. element = todo.pop(0)
  50. for node in element.childNodes:
  51. if node.nodeType == node.ELEMENT_NODE:
  52. todo.append(node)
  53. stroke = element.getAttribute("stroke")
  54. strokewidth = element.getAttribute("stroke-width")
  55. if len(stroke) == 0:
  56. style = element.getAttribute("style")
  57. if len(style) != 0:
  58. style = style.replace(";", ":")
  59. styles = style.split(":")
  60. for index, name in enumerate(styles):
  61. if name == "stroke":
  62. stroke = styles[index + 1]
  63. elif name == "stroke-width":
  64. strokewidth = styles[index + 1]
  65. if len(stroke) > 0 and stroke != "none":
  66. if len(strokewidth) == 0:
  67. print "no stroke width", svgFilename # ,
  68. if fix != "yes":
  69. break
  70. # print "fixing", element.toxml("UTF-8")
  71. element.setAttribute("stroke-width", "1")
  72. changed = 1
  73. if changed:
  74. outfile = open(svgFilename, 'wb')
  75. s = dom.toxml("UTF-8")
  76. outfile.write(s)
  77. outfile.flush()
  78. outfile.close()
  79. if __name__ == "__main__":
  80. main()