Debian Codegraph @

eyes17/screenshots/printableSVG.py

raw
1 #! /usr/bin/python3
2
3 import sys, re
4 from copy import deepcopy
5
6 def isScreenBg(line):
7 """
8 :param line: a string with some SVG element
9 :returns: True if the element is an image which contains the
10 screen's background
11 """
12 if "image" not in line:
13 return False
14 m=re.match(r'.*width="(\d+)".*', line)
15 if m:
16 width=int(m.group(1))
17 return width > 500
18 return False
19
20 def ligthenOneLine(l):
21 """
22 process one line to make it a line of the lighter SVG file
23 :param l: one line
24 :returns: the processed line, eventually an empty string
25 """
26 if isScreenBg(l):
27 return ""
28 # substitute some colors and a few widths
29 sub = [
30 ('fill="#ffff00"', 'fill="#000000"'),
31 ('g fill="#008000"', 'g fill="#0000ff"'),
32 ('stroke="#22648d"', 'stroke="#ababab"'),
33 ('stroke="#00ff00" stroke-opacity="1" stroke-width="1"',
34 'stroke="#0000ff" stroke-opacity="1" stroke-width="2"'),
35 ('stroke="#ffff00"', 'stroke="#000000"'),
36 ('stroke="#ff00ff" stroke-opacity="1" stroke-width="1"',
37 'stroke="#00ff00" stroke-opacity="1" stroke-width="2"'),
38 ('stroke="#00ffff" stroke-opacity="1" stroke-width="1"',
39 'stroke="#00ff00" stroke-opacity="1" stroke-width="2"'),
40 ('g fill="none" stroke="#0000ff"', 'g fill="none" stroke="#ff0000"'),
41 ('g fill="none" stroke="#ff0000"', 'g fill="none" stroke="#ff00ff"'),
42 ('g fill="none" stroke="#000000" stroke-opacity="1" stroke-width="1"',
43 'g fill="none" stroke="#000000" stroke-opacity="1" stroke-width="2"'),
44 ]
45 for s in sub:
46 l=l.replace(*s)
47 return l
48
49 def lightenSvgFile(inFname, outFname=""):
50 """
51 Writes a SVG file for printing usage
52 :param inFname: the name of the input file
53 :param outFname: the name of the ouput file or an empty string
54 :returns: the actual name of the output file, eventually composed
55 by modifying the input file name
56 """
57 if not outFname:
58 # create outFname based on inFname
59 if "-screen" in inFname:
60 outFname = inFname.replace("-screen", "-print")
61 else:
62 outFname = inFname.replace(".svg", "")+"-print.svg"
63 if "-dark" in outFname:
64 outFname = outFname.replace("-dark", "")
65 with open(inFname) as infile, open(outFname,"w") as outfile:
66 l=infile.readline()
67 while l:
68 outfile.write(ligthenOneLine(l))
69 l=infile.readline()
70 return outFname
71
72 def openSVG(path):
73 """
74 opens a SVG file and returns its main element, together with width and
75 height of the viewport.
76 :param path: the path to a SVG file
77 :return: a tuple with the SVG contents, width and height of the viewport
78 :rtype: (xml.dom.Element, int, int)
79 """
80 from xml.dom import minidom
81 doc = minidom.parse(open(path))
82 svg = doc.getElementsByTagName("svg")[0]
83 sizeMatch = re.match(r"(\d+) (\d+) (\d+) (\d+)", svg.getAttribute("viewBox"))
84 w, h = int(sizeMatch.group(3)), int(sizeMatch.group(4))
85 return svg, w, h
86
87 def fixNonScalingStroke(path):
88 """
89 fix the stroke width for SVG readers which cannot honor the attribute
90 'vector-effect = "non-scaling-stroke"' and render the oscilloscope's
91 traces too wide.
92 :param path: the path to a SVG file which has to be modified on place
93 """
94 svg, w, h = openSVG(path)
95 groups = svg.getElementsByTagName("g")
96 # first remove childless groups
97 childless = [g for g in groups if len([el for el in g.childNodes if el.nodeType != 3]) == 0] # 3 is the value of TEXT_NODE
98 removed=[]
99 for g in childless:
100 g.parentNode.removeChild(g)
101 removed.append(g)
102 for g in removed:
103 g.unlink()
104 # reload the group list and keep only groups with big transform matrices
105 groups = [g for g in svg.getElementsByTagName("g")
106 if float("0"+"".join(re.findall(r"matrix\((\d+)", g.getAttribute("transform")))) > 2]
107 ## find the groups containing a single path
108 for g in groups:
109 paths = g.getElementsByTagName("path")
110 if len(paths) == 1:
111 moves=paths[0].getAttribute("d")
112 # get the matrix transformation, remove it from
113 # g's transform attribute and apply it to the path
114 m = g.getAttribute("transform")
115 g.removeAttribute("transform")
116 g.setAttribute("data-export", "applied the matrix")
117 a, b, c, d, e, f = re.findall(r"([.\-\d]+)", m)
118 a = float(a)
119 b = float(b)
120 c = float(c)
121 d = float(d)
122 e = float(e)
123 f = float(f)
124 paths[0].removeAttribute("vector-effect")
125 paths[0].removeAttribute("fill-rule")
126 new_moves = "M"
127 coords = re.findall(r"\S([.\-\d]+,[.\-\d]+) *", moves[1:])
128 ### As documented by
129 ### https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
130 for x_comma_y in coords:
131 x, y = x_comma_y.split(sep = ",")
132 x = float(x)
133 y = float(y)
134 x_new = a * x + c * y + e
135 y_new = b * x + d * y + f
136 new_moves += f" {x_new:6f},{y_new:6f}"
137 paths[0].setAttribute("d", new_moves)
138 with open(path,"w") as outfile:
139 outfile.write('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
140 outfile.write(svg.toxml())
141 return
142
143 def svg2png (fName, width=600, app=None, oFilename=""):
144 """
145 Smart convertion to PNG files; stroke widths are widened when necessary,
146 so traces on an oscilloscope screen will be visible even if it is
147 downscaled. A PNG file is written.
148 :param fname: file name of a SVG drawing
149 :param width: the width of the wanted PNG drawing; its height will be
150 :param app: the current application
151 :param oFilename: facultative file name for the output PNG file
152 calculated automatically
153 :returns: the effective file name of the written PNG file
154 """
155 from PyQt5.QtSvg import QSvgRenderer
156 from PyQt5.QtGui import QImage, QPainter, QColor, QGuiApplication
157 from math import sqrt
158
159 if not app:
160 app=QGuiApplication([])
161 svg, w, h = openSVG(fName)
162 groups = svg.getElementsByTagName("g")
163 scale = width/w
164 for g in groups:
165 if "stroke-width" in g.attributes:
166 g.setAttribute("stroke-width", str(float(g.getAttribute("stroke-width"))/sqrt(scale)))
167 qsr=QSvgRenderer(svg.toxml().encode("utf-8"))
168 img=QImage(int(w*scale), int(h*scale), QImage.Format_ARGB32)
169 img.fill(QColor("white"))
170 p=QPainter(img)
171 qsr.render(p)
172 p.end()
173 if not oFilename:
174 oFilename = re.sub(r"\.svg$", f"-{width}px.png", fName)
175 img.save(oFilename)
176 return oFilename
177
178 def test_lighten():
179 outFname=""
180 if len(sys.argv) > 1:
181 inFname = sys.argv[1]
182 if len(sys.argv) > 2:
183 outFname = sys.argv[2]
184 outFname = lightenSvgFile(inFname, outFname)
185 print("Wrote", outFname)
186 return
187
188 def test_convert():
189 print("Wrote", svg2png(sys.argv[1], width=300))
190 return
191
192 if __name__ == "__main__":
193 test_convert()
194