Skip to content

Commit

Permalink
Now outputs nested elements at different indentations
Browse files Browse the repository at this point in the history
  • Loading branch information
petercollingridge committed Jun 19, 2011
1 parent 0607d03 commit 9f77192
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 9 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
*.pyc
*~
test.svg
22 changes: 15 additions & 7 deletions PySVG.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
# ***To do**
# Styles
# Scripts
# Prefered order for output
# Nesting parameter
# Automatic id generation

class SVG_Element:
""" Generic element with attributes and potential child elements.
Outputs as <type attribute dict> child </type>."""
Expand All @@ -18,24 +25,24 @@ def __init__(self, type, attributes=None, child=None):
def addChildElement(self, type, attributes=None, child=None):
self.children.append(SVG_Element(type, attributes, child))

def output(self):
svg_string = '<%s' % (self.type)
def output(self, nesting=0):
svg_string = ' '*nesting + '<%s' % (self.type)

for key, value in self.attributes.items():
svg_string += ' %s="%s"' % (key, value)

if not self.children:
svg_string += '/>'
svg_string += '/>\n'
else:
svg_string += '>\n'

for child in self.children:
if isinstance(child, SVG_Element):
svg_string += child.output()
svg_string += child.output(nesting+1)
else:
svg_string += '%s\n' % child
svg_string += ' '*(nesting+1) + '%s\n' % child

svg_string += '</%s>\n' % (self.type)
svg_string += ' '*nesting + '</%s>\n' % (self.type)


return svg_string
Expand All @@ -47,9 +54,10 @@ def __init__(self, attributes=None):
SVG_Element.__init__(self, 'svg', attributes)
self.attributes['version'] = 1.1
self.attributes['xmlns'] = 'http://www.w3.org/2000/svg'
self.attributes['xmlns:xlink'] = 'http://www.w3.org/1999/xlink'

def output(self):
svg_string = '<?xml version="1.0" standalone="no"?>\n'
svg_string = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n'
svg_string += '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'

svg_string += SVG_Element.output(self)
Expand Down
7 changes: 5 additions & 2 deletions examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,8 @@
my_svg = PySVG.SVG({'width':600})
my_svg.attributes['height'] = 400

my_svg.addChildElement('rect', {'x':10, 'y':15, 'id':'rect-1'}, 'child')
print my_svg.output()
my_svg.addChildElement('Text', {'id':'text-1', 'x':10, 'y':15}, 'This is a child')
my_svg.addChildElement('rect', {'id':'rect-2', 'x':20, 'y':25, 'width':20, 'height':25, 'fill':'blue'})

fout = file('test.svg', 'w')
fout.write(my_svg.output())

0 comments on commit 9f77192

Please sign in to comment.