-
Notifications
You must be signed in to change notification settings - Fork 726
Expand file tree
/
Copy pathsvg.py
More file actions
192 lines (154 loc) · 5.64 KB
/
svg.py
File metadata and controls
192 lines (154 loc) · 5.64 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
from __future__ import annotations
import decimal
from decimal import Decimal
from typing import TYPE_CHECKING, Literal, overload
import qrcode.image.base
from qrcode.compat.etree import ET
from qrcode.image.styles.moduledrawers import svg as svg_drawers
if TYPE_CHECKING:
from qrcode.image.styles.moduledrawers.base import QRModuleDrawer
class SvgFragmentImage(qrcode.image.base.BaseImageWithDrawer):
"""
SVG image builder
Creates a QR-code image as a SVG document fragment.
"""
_SVG_namespace = "http://www.w3.org/2000/svg"
kind = "SVG"
allowed_kinds = ("SVG",)
default_drawer_class: type[QRModuleDrawer] = svg_drawers.SvgSquareDrawer
def __init__(self, *args, **kwargs):
ET.register_namespace("svg", self._SVG_namespace)
super().__init__(*args, **kwargs)
# Save the unit size, for example the default box_size of 10 is '1mm'.
self.unit_size = self.units(self.box_size)
@overload
def drawrect(self, row, col):
"""
Not used.
"""
@overload
def units(self, pixels: int | Decimal, text: Literal[False]) -> Decimal: ...
@overload
def units(self, pixels: int | Decimal, text: Literal[True] = True) -> str: ...
def units(self, pixels: int, text=True) -> Decimal | str:
"""
Converts pixel values into a decimal representation with up to three decimal
places of precision or a string representation, optionally rounding to
lower precision without data loss.
"""
units = Decimal(pixels)
if not text:
return units
# Round the decimal to 3 decimal places first, then try to reduce precision
# further by attempting to round to 2 decimals, 1 decimal, and whole numbers.
# If any rounding causes data loss (raises Inexact), keep the previous
# precision.
units = units.quantize(Decimal("0.001"))
context = decimal.Context(traps=[decimal.Inexact])
try:
for d in (Decimal("0.01"), Decimal("0.1"), Decimal(0)):
units = units.quantize(d, context=context)
except decimal.Inexact:
pass
return str(units)
def save(self, stream, kind=None):
self.check_kind(kind=kind)
self._write(stream)
def to_string(self, **kwargs):
return ET.tostring(self._img, **kwargs)
def new_image(self, **kwargs):
return self._svg(**kwargs)
def _svg(self, tag=None, version="1.1", **kwargs):
if tag is None:
tag = ET.QName(self._SVG_namespace, "svg")
dimension = self.units(self.pixel_size, text=False)
viewBox = kwargs.get("viewBox", f"0 0 {dimension} {dimension}")
kwargs["viewBox"] = viewBox
return ET.Element(
tag,
version=version,
**kwargs,
)
def _write(self, stream):
ET.ElementTree(self._img).write(stream, xml_declaration=False)
class SvgImage(SvgFragmentImage):
"""
Standalone SVG image builder
Creates a QR-code image as a standalone SVG document.
"""
background: str | None = None
drawer_aliases: qrcode.image.base.DrawerAliases = {
"circle": (svg_drawers.SvgCircleDrawer, {}),
"gapped-circle": (svg_drawers.SvgCircleDrawer, {"size_ratio": Decimal("0.8")}),
"gapped-square": (svg_drawers.SvgSquareDrawer, {"size_ratio": Decimal("0.8")}),
}
def _svg(self, tag="svg", **kwargs):
svg = super()._svg(tag=tag, **kwargs)
svg.set("xmlns", self._SVG_namespace)
if self.background:
svg.append(
ET.Element(
"rect",
fill=self.background,
x="0",
y="0",
width="100%",
height="100%",
)
)
return svg
def _write(self, stream):
ET.ElementTree(self._img).write(stream, encoding="UTF-8", xml_declaration=True)
class SvgPathImage(SvgImage):
"""
SVG image builder with one single <path> element (removes white spaces
between individual QR points).
"""
QR_PATH_STYLE = {
"fill": "#000000",
"fill-opacity": "1",
"fill-rule": "nonzero",
"stroke": "none",
}
needs_processing = True
path: ET.Element | None = None
default_drawer_class: type[QRModuleDrawer] = svg_drawers.SvgPathSquareDrawer
drawer_aliases = {
"circle": (svg_drawers.SvgPathCircleDrawer, {}),
"gapped-circle": (
svg_drawers.SvgPathCircleDrawer,
{"size_ratio": Decimal("0.8")},
),
"gapped-square": (
svg_drawers.SvgPathSquareDrawer,
{"size_ratio": Decimal("0.8")},
),
}
def __init__(self, *args, **kwargs):
self._subpaths: list[str] = []
super().__init__(*args, **kwargs)
def _svg(self, viewBox=None, **kwargs):
if viewBox is None:
dimension = self.units(self.pixel_size, text=False)
viewBox = f"0 0 {dimension} {dimension}"
return super()._svg(viewBox=viewBox, **kwargs)
def process(self):
# Store the path just in case someone wants to use it again or in some
# unique way.
self.path = ET.Element(
ET.QName("path"),
d="".join(self._subpaths),
**self.QR_PATH_STYLE,
)
self._subpaths = []
self._img.append(self.path)
class SvgFillImage(SvgImage):
"""
An SvgImage that fills the background to white.
"""
background = "white"
class SvgPathFillImage(SvgPathImage):
"""
An SvgPathImage that fills the background to white.
"""
background = "white"