MCPcopy Create free account
hub / github.com/WhyNotHugo/python-barcode / SVGWriter

Class SVGWriter

barcode/writer.py:310–413  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

308
309
310class SVGWriter(BaseWriter):
311 def __init__(self) -> None:
312 super().__init__(
313 self._init,
314 self._create_module,
315 self._create_text,
316 self._finish,
317 )
318 self.compress: bool = False
319 self.with_doctype: bool = True
320 self._document: xml.dom.minidom.Document
321 self._root: xml.dom.minidom.Element
322 self._group: xml.dom.minidom.Element
323
324 def _init(self, code: list[str]):
325 if len(code) != 1:
326 raise NotImplementedError("Only one line of code is supported")
327 line = code[0]
328 width, height = self.calculate_size(len(line), 1)
329 self._document = create_svg_object(self.with_doctype)
330 self._root = self._document.documentElement
331 attributes = {
332 "width": SIZE.format(width),
333 "height": SIZE.format(height),
334 }
335 _set_attributes(self._root, **attributes)
336 if COMMENT:
337 self._root.appendChild(self._document.createComment(COMMENT))
338 # create group for easier handling in 3rd party software
339 # like corel draw, inkscape, ...
340 group = self._document.createElement("g")
341 attributes = {"id": "barcode_group"}
342 _set_attributes(group, **attributes)
343 self._group = self._root.appendChild(group)
344 if self.background is not None:
345 background = self._document.createElement("rect")
346 attributes = {
347 "width": "100%",
348 "height": "100%",
349 "style": f"fill:{self.background}",
350 }
351 _set_attributes(background, **attributes)
352 self._group.appendChild(background)
353
354 def _create_module(self, xpos, ypos, width, color):
355 # Background rect has been provided already, so skipping "spaces"
356 if color != self.background:
357 element = self._document.createElement("rect")
358 attributes = {
359 "x": SIZE.format(xpos),
360 "y": SIZE.format(ypos),
361 "width": SIZE.format(width),
362 "height": SIZE.format(self.module_height),
363 "style": f"fill:{color};",
364 }
365 _set_attributes(element, **attributes)
366 self._group.appendChild(element)
367

Calls

no outgoing calls