Open
Description
from lxml import etree
# reference: https://shayallenhill.com/svg-with-css-in-python/
def new_svg():
my_root_element = etree.Element(
"svg", width='640', height='480', xmlns="http://www.w3.org/2000/svg"
)
# let's draw a rectangle
my_rectangle = etree.Element(
# the svg element type
"rect",
# any svg parameters that happen to be valid
# Python attribute names
x="13",
y="14",
width="500",
height="200",
rx="50",
ry="100",
stroke="blue",
)
my_root_element.append(my_rectangle)
# another rectangle
my_rectangle_string = etree.fromstring(
f'<rect class="some-css-class" x="13" y="214" width="500" height="200" stroke="red" />'
)
my_root_element.append(my_rectangle_string)
# we must add style
style = etree.Element("style", type="text/css")
style.text = etree.CDATA("/** some CSS **/")
my_root_element.insert(0, style)
# generate svg content string
return etree.tostring(
etree.ElementTree(my_root_element),
xml_declaration=True,
doctype=(
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
'"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">'
),
)
# Writing a file
f = open('file.svg', 'wb+')
f.write(new_svg())
f.close()