Created
December 3, 2023 00:36
-
-
Save TruncatedDinoSour/83f324cb156ca8cd58284d436a0d9f75 to your computer and use it in GitHub Desktop.
convert text to svg without libraries in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
nice work, this saved me a lot of time - thanks for putting it up!