Skip to content

Instantly share code, notes, and snippets.

@TruncatedDinoSour
Created December 3, 2023 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TruncatedDinoSour/83f324cb156ca8cd58284d436a0d9f75 to your computer and use it in GitHub Desktop.
Save TruncatedDinoSour/83f324cb156ca8cd58284d436a0d9f75 to your computer and use it in GitHub Desktop.
convert text to svg without libraries in python
# this is taken from one of my projects, i have no clue how i got here
# but i did, maybe some of u can refine it and use it, but here it is
from html import escape as html_escape
def text2svg(
text: str,
fill: str = "#fff",
font: str = "sans-serif",
size: float = 16,
baseline: float = 1,
padding: float = 1,
ratio: float = 1, # usually 2 for monospace
) -> str:
"""convert count to svg
fill -- text colour
font -- font family
size -- font size in pixels
baseline -- baseline offset
padding -- padding of characters
ratio -- character ratio
embedding :
<img
id="my-stuff"
src="..."
style="display:inline;height:1em;vertical-align:top"
alt="my stuff :3"
/>
"""
fill = html_escape(fill)
font = html_escape(font)
svg: str = f'<svg xmlns="http://www.w3.org/2000/svg" width="{len(text) + padding * ratio}ch" height="{size}" font-size="{size}">'
svg += f'<text x="50%" y="{size - baseline}" text-anchor="middle" fill="{fill}" font-family="{font}">{html_escape(text)}</text>'
svg += "</svg>"
return svg
@chriswbartley
Copy link

nice work, this saved me a lot of time - thanks for putting it up!

@TruncatedDinoSour
Copy link
Author

nice work, this saved me a lot of time - thanks for putting it up!

any day :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment