Skip to content

Instantly share code, notes, and snippets.

@KowalskiThomas
Last active October 31, 2019 10:42
Show Gist options
  • Save KowalskiThomas/db00ff2705cf83a985fb09e6314fea9e to your computer and use it in GitHub Desktop.
Save KowalskiThomas/db00ff2705cf83a985fb09e6314fea9e to your computer and use it in GitHub Desktop.
SVG Viewbox Recentering
import os
for file in os.listdir("."):
if not file.endswith(".svg"):
continue
print("Traitement", file)
try:
with open(file, 'r') as f:
content = f.read()
lines = content.split('\n')
assert len(lines) > 1, "Seuls les fichiers XML indentés / sur plusieurs lignes sont supportés"
first_line = lines[0]
s = first_line.split()
hOffset = s[-4].replace('viewBox="', '')
vOffset = s[-3]
width = s[-2]
height = s[-1].replace('">', '')
hOffset = float(hOffset)
vOffset = float(vOffset)
height = float(height)
width = float(width)
parameter = str(max(height, width))
difference = max(height, width) - min(height, width)
if height > width:
hOffset -= difference / 2
else:
vOffset -= difference / 2
s[-4] = 'viewBox="{}'.format(hOffset)
s[-3] = vOffset
s[-2] = parameter
s[-1] = '{}">'.format(parameter)
s = list(map(str, s))
first_line = " ".join(s)
third_line = lines[2]
third_line = third_line.replace("<style>", '<style type="text/css">')
lines[2] = third_line;
lines[0] = first_line
content = "\n".join(lines)
if not os.path.exists('output'):
os.mkdir('output')
with open('output/{}'.format(file), 'w') as f:
f.write(content)
except Exception as e:
print("Erreur avec {}".format(file), type(e), e)
print("OK")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment