-
Notifications
You must be signed in to change notification settings - Fork 4
/
svg_diagram.py
86 lines (69 loc) · 2.23 KB
/
svg_diagram.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
from io import BytesIO, StringIO
import svgwrite
import reportlab.graphics.shapes as reportlab_shapes
from cairosvg import svg2png
from reportlab.graphics.renderPM import drawToFile
from svglib.svglib import svg2rlg
from diagram import draw_diagram
from svg_turtle import SvgTurtle
class SvgDiagram:
def __init__(self, width="400px", height="250px"):
if not isinstance(width, str):
width = f'{width}px'
if not isinstance(height, str):
height = f'{height}px'
self.svg_drawing = svgwrite.Drawing(size=(width, height))
self.turtle = SvgTurtle(self.svg_drawing)
def to_reportlab(self) -> reportlab_shapes.Drawing:
svg_text = self.turtle.to_svg()
svg_bytes = svg_text.encode()
drawing = svg2rlg(BytesIO(svg_bytes))
return drawing
def to_cairo(self, png_file: str):
svg2png(file_obj=StringIO(self.turtle.to_svg()),
write_to=png_file,
background_color='transparent')
def draw_page(turtle, state):
lines = state.split('\n---\n')[0].splitlines()
row_count = (len(lines) + 1) // 2
column_count = (max(len(line) for line in lines) + 1) // 2
width = turtle.screen.window_width()
height = turtle.screen.window_height()
cell_size = min(width/column_count, height/row_count)
turtle.up()
turtle.back(cell_size*column_count/2)
turtle.right(90)
turtle.back(cell_size*row_count/2)
turtle.left(90)
draw_diagram(turtle, state, cell_size)
def main():
state = """\
0 1 4 3 1 2 4|6
- - - - - -
1 4 3 1 2 4 0|6
0|3 2|5 5|5 5|1
3|6 0|2 2|6 6|1
6|5 6|6 0|4 3|3
5 2 0|0 4|4 2|2
- -
3 3 1|1 0|5 5|4
"""
# cell size of 60 looks good on puzzling.se.
diagram = SvgDiagram('480', '420')
bg = None
if bg:
diagram.svg_drawing.add(
diagram.svg_drawing.rect(fill='bg', size=("100%", "100%")))
draw_page(diagram.turtle, state)
is_svg = False
is_cairo = False
if is_svg:
diagram.svg_drawing.saveas('diagram.svg')
elif is_cairo:
diagram.to_cairo('docs/images/example.png')
else:
drawing = diagram.to_reportlab()
drawToFile(drawing, 'docs/images/example.png', 'PNG')
print('Done.')
if __name__ == '__main__':
main()