mathandy / svgpathtools

A collection of tools for manipulating and analyzing SVG Path objects and Bezier curves.
MIT License
532 stars 134 forks source link

[Feature Request] svgpathtools.Document.paths() API for retrieving path style attributes #177

Open pietakio opened 2 years ago

pietakio commented 2 years ago

svgpathtools is phenomenal! But svgpathtools might be even more phenomenal if the svgpathtools.path.Path class underlying the svgpathtools.Document.paths() API provided a styles instance variable (...or something). Path.style would be a Pythonic dictionary mapping from the name to value of each path style, trivially parsed from the ;- and :-delimited SVG style attribute for each path.

Working code or it didn't happen. So, I envision an API resembling this:

import svgpathtools

# For each path defined by a test SVG file...
for path in svgpathtools.Document('test.svg').paths():
    # List of all ":"-delimited style subattributes for this path.
    path_styles_raw = path.element.get('style').split(';')

    # Dictionary mapping from the name to stringified value of each
    # style subattribute for this path.
    path.styles = {}

    # For each ":"-delimited style subattribute for this path...
    for path_style_raw in path_styles_raw:
        # Split this subattribute into its constituent name and value.
        path_style_key, path_style_value = path_style_raw.split(':')

        # Map this subattribute name to this value.
        path.styles[path_style_key] = path_style_value

That then results in a path.styles dictionary for each SVG path resembling:

>>> print(path.styles)
{'opacity': '1', 'fill': '#ffb380', 'fill-opacity': '1', 'stroke': '#ffb380', 'stroke-width': '0.74810636', 'stroke-linecap': 'butt', 'stroke-linejoin': 'miter', 'stroke-miterlimit': '4', 'stroke-dasharray': 'none', 'stroke-dashoffset': '0', 'stroke-opacity': '1', 'paint-order': 'normal'}

In theory, something along those lines should be trivial. I note that the experimental svgpathtools.svg_io_sax.SaxDocument class already contains similar logic. But I defer to your magnanimous wisdom in all things SVG, as always.

Thanks so much for the continual volunteerism, @mathandy! You make the hard SVG things that much easier. :+1: