benjamin-chat / backend /svg_processing.py
Gregor Betz
First code commit
8bd8cd0
import re
# check: https://github.com/vasturiano/d3-zoomable/blob/master/example/svg/index.html
def remove_links_svg(svg):
svg = svg.replace("</a>","")
svg = svg.replace("\n\n","\n")
regex = r"<a xlink[^>]*>"
svg = re.sub(regex, "", svg, count=0, flags=re.MULTILINE)
return svg
def resize_svg(svg, max_width=800):
regex = r"<svg width=\"(?P<width>[\d]+)pt\" height=\"(?P<height>[\d]+)pt\""
match = next(re.finditer(regex, svg, re.MULTILINE))
width = int(match.group("width"))
height = int(match.group("height"))
if width <= max_width:
return svg
scale = max_width / width
s_width = round(scale * width)
s_height = round(scale * height)
s_svg = svg.replace(match.group(), f'<svg width="{s_width}pt" height="{s_height}pt"')
return s_svg
def postprocess_svg(svg):
if not svg:
return ""
svg = "<svg" + svg.split("<svg", maxsplit=1)[1]
svg = remove_links_svg(svg)
svg = resize_svg(svg, max_width=800)
return svg