|
| 1 | +"""Helper functions to manipulate Inkscape SVG content. |
| 2 | +
|
| 3 | +Original version can be found at https://github.com/letuananh/pyinkscape |
| 4 | +
|
| 5 | +@author: Le Tuan Anh <tuananh.ke@gmail.com> |
| 6 | +@license: MIT |
| 7 | +""" |
| 8 | + |
| 9 | +# Copyright (c) 2017, Le Tuan Anh <tuananh.ke@gmail.com> |
| 10 | +# |
| 11 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 12 | +# of this software and associated documentation files (the "Software"), to deal |
| 13 | +# in the Software without restriction, including without limitation the rights |
| 14 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 15 | +# copies of the Software, and to permit persons to whom the Software is |
| 16 | +# furnished to do so, subject to the following conditions: |
| 17 | +# |
| 18 | +# The above copyright notice and this permission notice shall be included in |
| 19 | +# all copies or substantial portions of the Software. |
| 20 | +# |
| 21 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 22 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 23 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 24 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 25 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 26 | +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 27 | +# THE SOFTWARE. |
| 28 | + |
| 29 | +######################################################################## |
| 30 | + |
| 31 | +import logging |
| 32 | +import os |
| 33 | +import typing as tp |
| 34 | +from xml.dom.minidom import Element |
| 35 | + |
| 36 | +from lxml import etree |
| 37 | +from lxml.etree import XMLParser |
| 38 | + |
| 39 | +_BLANK_CANVAS = os.path.join(os.path.dirname(os.path.realpath(__file__)), "blank.svg") |
| 40 | + |
| 41 | +logger = logging.getLogger(__name__) |
| 42 | +logging.basicConfig() |
| 43 | +logger.setLevel(logging.INFO) |
| 44 | + |
| 45 | +INKSCAPE_NS = "http://www.inkscape.org/namespaces/inkscape" |
| 46 | +SVG_NS = "http://www.w3.org/2000/svg" |
| 47 | +SVG_NAMESPACES = { |
| 48 | + "ns": SVG_NS, |
| 49 | + "svg": SVG_NS, |
| 50 | + "dc": "http://purl.org/dc/elements/1.1/", |
| 51 | + "cc": "http://creativecommons.org/ns#", |
| 52 | + "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", |
| 53 | + "sodipodi": "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd", |
| 54 | + "inkscape": INKSCAPE_NS, |
| 55 | +} |
| 56 | +XLINK_NS = "http://www.w3.org/1999/xlink" |
| 57 | + |
| 58 | + |
| 59 | +class Point: |
| 60 | + def __init__(self, x: float, y: float): |
| 61 | + self.x = x |
| 62 | + self.y = y |
| 63 | + |
| 64 | + |
| 65 | +class Dimension: |
| 66 | + def __init__(self, width, height): |
| 67 | + self.width = width |
| 68 | + self.height = height |
| 69 | + |
| 70 | + |
| 71 | +class BBox: |
| 72 | + """A bounding box represents by a top-left anchor (x1, y1) and a dimension (width, height)""" |
| 73 | + |
| 74 | + def __init__(self, x, y, width, height): |
| 75 | + self._anchor = Point(x, y) |
| 76 | + self._dimension = Dimension(width, height) |
| 77 | + |
| 78 | + @property |
| 79 | + def width(self): |
| 80 | + """Width of the bounding box""" |
| 81 | + return self._dimension.width |
| 82 | + |
| 83 | + @property |
| 84 | + def height(self): |
| 85 | + """Height of the bounding box""" |
| 86 | + return self._dimension.height |
| 87 | + |
| 88 | + |
| 89 | +class Canvas: |
| 90 | + """This class represents an Inkscape drawing page (i.e. a SVG file).""" |
| 91 | + |
| 92 | + def __init__(self, filepath=tp.Optional[str], *args, **kwargs): |
| 93 | + """Create a new blank canvas or read from an existing file. |
| 94 | +
|
| 95 | + To create a blank canvas, just ignore the filepath property. |
| 96 | + >>> c = Canvas() |
| 97 | +
|
| 98 | + To open an existing file, use |
| 99 | + >>> c = Canvas("/path/to/file.svg") |
| 100 | +
|
| 101 | + Arguments: |
| 102 | + filepath: Path to an existing SVG file. |
| 103 | + """ |
| 104 | + self._filepath = filepath |
| 105 | + self._tree = None |
| 106 | + self._root = None |
| 107 | + self._units = "mm" |
| 108 | + self._width = 0 |
| 109 | + self._height = 0 |
| 110 | + self._viewbox = None |
| 111 | + self._scale = 1.0 |
| 112 | + self._elem_group_map = {} |
| 113 | + self._elements_by_ids = {} |
| 114 | + if filepath is not None: |
| 115 | + self._load_file(*args, **kwargs) |
| 116 | + |
| 117 | + def _load_file(self, remove_blank_text=True, encoding="utf-8", **kwargs): |
| 118 | + with open( |
| 119 | + _BLANK_CANVAS if not self._filepath else self._filepath, |
| 120 | + encoding=encoding, |
| 121 | + ) as infile: |
| 122 | + kwargs["remove_blank_text"] = remove_blank_text # lxml specific |
| 123 | + parser = XMLParser(**kwargs) |
| 124 | + self._tree = etree.parse(infile, parser) |
| 125 | + self._root = self._tree.getroot() |
| 126 | + self._update_svg_info() |
| 127 | + |
| 128 | + def _update_svg_info(self): |
| 129 | + # load SVG information |
| 130 | + if self._svg_node.get("viewBox"): |
| 131 | + self._viewbox = BBox( |
| 132 | + *(float(x) for x in self._svg_node.get("viewBox").split()) |
| 133 | + ) |
| 134 | + if not self._width: |
| 135 | + self._width = self._viewbox.width |
| 136 | + if not self._height: |
| 137 | + self._width = self._viewbox.height |
| 138 | + if self.viewBox and self._width: |
| 139 | + self._scale = self.viewBox.width / self._width |
| 140 | + |
| 141 | + @property |
| 142 | + def _svg_node(self): |
| 143 | + return self._root |
| 144 | + |
| 145 | + @property |
| 146 | + def viewBox(self): |
| 147 | + return self._viewbox |
| 148 | + |
| 149 | + def to_xml_string(self, encoding="utf-8", pretty_print=True, **kwargs): |
| 150 | + return etree.tostring( |
| 151 | + self._root, |
| 152 | + encoding=encoding, |
| 153 | + pretty_print=pretty_print, |
| 154 | + **kwargs, |
| 155 | + ).decode("utf-8") |
| 156 | + |
| 157 | + def _xpath_query(self, query_string, namespaces=None): |
| 158 | + return self._root.xpath(query_string, namespaces=namespaces) |
| 159 | + |
| 160 | + def element_by_id(self, id: str) -> tp.Optional[Element]: |
| 161 | + """Get one XML element by its ID. |
| 162 | +
|
| 163 | + Arguments: |
| 164 | + id: the ID of the element |
| 165 | +
|
| 166 | + Raises: |
| 167 | + RuntimeError: when more than two elements share the exact same ID |
| 168 | + """ |
| 169 | + elements = self._xpath_query(f".//ns:*[@id='{id}']", namespaces=SVG_NAMESPACES) |
| 170 | + if not elements: |
| 171 | + return None |
| 172 | + if len(elements) > 1: |
| 173 | + raise RuntimeError(f"Found {len(elements)} elements with the same id {id}") |
| 174 | + return elements[0] |
| 175 | + |
| 176 | + def render(self, outpath, overwrite=False, encoding="utf-8"): |
| 177 | + if not overwrite and os.path.isfile(outpath): |
| 178 | + logger.warning(f"File {outpath} exists. SKIPPED") |
| 179 | + else: |
| 180 | + output = self.to_xml_string(pretty_print=False) |
| 181 | + with open(outpath, mode="w", encoding=encoding) as outfile: |
| 182 | + outfile.write(output) |
| 183 | + logger.info("Written output to {}".format(outfile.name)) |
0 commit comments