Search code examples
pythonsvginkscapesvgwrite

Adding text into groups does not work for svgwrite


I'm writing some basic script to create basic charts using python's svgwrite. I have successfully been able to create groups with other items, such as circles, paths and lines. However when adding several text elements into a group those are not properly shown in a group when I open the svg figure with Inkscape. The text shows up all right, but it is just not grouped.

This is my piece of code:

        # Create group for constellation names
        const_names = dwg.add(dwg.g(id='constellation_names', 
                                    stroke='none',
                                    fill=config.constellation_name_font.color.get_hex_rgb(),
                                    fill_opacity=config.constellation_name_font.color.get_float_alpha(),
                                    font_size=config.constellation_name_font.size*pt,
                                    font_family=config.constellation_name_font.font_family))
        
        log.warning("Constellation name groups are not working!")
        
        if config.constellation_name_enable:
            w, h = constellation.get_mean_position()
            # Add every text item into the group
            const_names.add(dwg.text(constellation.name,
                                     insert=(w*pt, h*pt),
                                     )
        )

Solution

  • Turns out this was a type-8 error (I had a bug on the code). This is how my code ended up looking like. All text instances are grouped on a single group.

    def _add_constellation_names(dwg, constellations, config):
        const_names = dwg.add(dwg.g(id='constellation_names', 
                                    stroke='none',
                                    fill=config.constellation_name_font.color.get_hex_rgb(),
                                    fill_opacity=config.constellation_name_font.color.get_float_alpha(),
                                    font_size=config.constellation_name_font.size*pt,
                                    font_family=config.constellation_name_font.font_family))
        
        for constellation in constellations:
            kwargs = {}
            if constellation.custom_color != None:
                kwargs["fill"] = constellation.custom_color.get_hex_rgb()
                kwargs["fill_opacity"] = constellation.custom_color.get_float_alpha()
            
            w, h = constellation.get_mean_position()
            const_names.add(dwg.text(constellation.get_display_name(),
                                     insert=(w*pt, h*pt),
                                     text_anchor="middle",
                                     **kwargs,
                                     )
                            )