Reputation: 7225
How can I convert an SVG to use inline styles in Python? For example, I want to convert this:
<svg xmlns="http://www.w3.org/2000/svg" id="Layer_1" data-name="Layer 1" viewBox="0 0 576 576">
<defs>
<style>.cls-1{fill:#d1b037;stroke:#1e1e1e;stroke-width:0.25px;}</style>
</defs>
<rect class="cls-1" width="576" height="576"/>
</svg>
to
<svg xmlns="http://www.w3.org/2000/svg" id="Layer_1" data-name="Layer 1" viewBox="0 0 576 576">
<rect class="cls-1" width="576" height="576" fill='#d1b037' stroke='#1e1e1e' stroke-width='0.25px'/>
</svg>
This is a simple example. I need support different elements, such as path
along with multiple classes sharing the same set of attributes.
There are SVG/XML parsers in Python, but not any for parsing the style tag. If it's easier to do in another language/tool, I'd be OK with that.
Upvotes: 1
Views: 4006
Reputation: 1713
I wrote a simple tool that converts the most common defs/style-node-format-using-class-selectors SVGs into single-style-attribute SVGs: https://github.com/doom-goober/svg_style_attribute/tree/master
The tool scour: https://github.com/scour-project/scour then converts single-style-attribute SVGs into inline-style-attribute SVGs.
Using these two tools, you can go from basic defs/style-node SVGs to single-style-attribute SVGs to inline-style-attributes SVGs.
Upvotes: 1
Reputation: 110821
There is no automatic way of doing that - you have to couple a XML parser, so that you can get the contents of the style
tag, and then feed that to a CSS parser - like tinycss
(linked in the comments) -
Then it is up to you to retrieve the objects returned by the CSS parser and match the rules to the ramining SVG tags - and, on matches, copy the rules to its style
tag (or, as you want - assemple the XML attributes from the style rule as given by the parser).
That is some work, but given the docs of the CSS parser should be more or less straightforward.
Upvotes: 0