meerk40t / svgelements

SVG Parsing for Elements, Paths, and other SVG Objects.
MIT License
124 stars 28 forks source link

Replacing text on Text element #238

Open quancore opened 1 year ago

quancore commented 1 year ago

@tatarize Hi, I would like to translate the text in the SVG figures and insert the translation back into the Text element. For this, I am just replacing the text attribute on the Text class. But sometimes, the translated text can be longer than the original one and can collide with other elements and I need to detect collision. I did not find a way to make it. I tried to use bbox function of Text elements but this function returns the same bbox after I modified the text in the Text class. Do you have any suggestions? Thank you in advance.

Note: many Text element on my SVGs does not have width or height property.

tatarize commented 10 months ago

Calculating the bbox of a text object would require that you actually know the size of the element. This is actually really hard to do since it requires knowing the element and what it refers to, reading the truetype font and processing it accordingly. This is, quite decidedly, a really hard thing to do.

Depending on the level of professionalism or get-it-done-ness there are a couple options. We can use inkscape to convert the text doing text to path within an inkscape commandline call. If we have path objects, these can actually be successfully calculated.

So the idea would be that we parse through the svg.

Alternatively, we could just potentially force define the size of the text and tell the SVG to ensure that it fits in the box you give it. It might require using a viewport of an second embedded svg, or including some javascript if you have script access or so.

You can also guess that on average characters are going to be about the same width. There's kerning and spacing involved but typically text that is 20 characters is about twice as long as text that is 10 characters. If we scale that by 0.5, in theory it would be a bit less likely to hit.

Really you're going to have a lot of issues. Like you may well need to typeset the entire thing over again with a bunch of constraints because if the text object changed size and caused a collision even if you detect the collision you might well trigger another collision on the other side by changing that stuff.