modm_data.pdf2html.figure
1# Copyright 2022, Niklas Hauser 2# SPDX-License-Identifier: MPL-2.0 3 4import math 5import ctypes 6import pypdfium2 as pp 7from lxml import etree 8from ..utils import Rectangle, Point 9from ..pdf import Path, Image 10 11 12# The thinnest stroke width, about one pixel when rendered at 3x scale 13_HAIRLINE = 0.3 14 15 16def _n(value: float) -> str: 17 return f"{value:.2f}".rstrip("0").rstrip(".") 18 19 20def _color(node, name: str, rgba: int): 21 node.set(name, f"#{rgba >> 8:06x}") 22 if (alpha := rgba & 0xFF) < 0xFF: 23 node.set(f"{name}-opacity", _n(alpha / 0xFF)) 24 25 26class Figure: 27 def __init__(self, page, bbox: Rectangle, cbbox: Rectangle = None, paths: list = None): 28 self._page = page 29 self.bbox = bbox 30 self.cbbox = cbbox 31 self._type = "figure" 32 self._paths = paths or [] 33 34 def _xy(self, point) -> str: 35 # PDF has its origin in the bottom left corner, SVG in the top left 36 return f"{_n(point.x - self.bbox.left)} {_n(self.bbox.top - point.y)}" 37 38 def _svg_path(self, path: Path): 39 data, curve = [], [] 40 for point in path.points: 41 if point.type == Path.Type.BEZIER: 42 # Cubic curves consist of two control points and the end point 43 curve.append(self._xy(point)) 44 if len(curve) == 3: 45 data.append("C" + " ".join(curve)) 46 curve = [] 47 else: 48 data.append(("M" if point.type == Path.Type.MOVE else "L") + self._xy(point)) 49 node = etree.Element("path", d="".join(data)) 50 51 fill_mode, stroked = path.draw_mode 52 if fill_mode: 53 _color(node, "fill", path.fill) 54 if fill_mode == 1: 55 node.set("fill-rule", "evenodd") 56 else: 57 node.set("fill", "none") 58 if stroked: 59 _color(node, "stroke", path.stroke) 60 # The stroke width is not part of the path and must be scaled 61 m = path.matrix.get() 62 scale = math.sqrt(abs(m[0] * m[3] - m[1] * m[2])) 63 # PDF viewers draw strokes at least one device pixel wide, so that 64 # hairlines stay visible, which SVG renderers do not do 65 node.set("stroke-width", _n(max(path.width * scale, _HAIRLINE))) 66 if path.dashes: 67 node.set("stroke-dasharray", " ".join(_n(d * scale) for d in path.dashes)) 68 if path.cap != Path.Cap.BUTT: 69 node.set("stroke-linecap", "round" if path.cap == Path.Cap.ROUND else "square") 70 if path.join != Path.Join.MITER: 71 node.set("stroke-linejoin", path.join.name.lower()) 72 return node 73 74 def _svg_slanted_texts(self, chars): 75 """Text at an angle that is no multiple of 90°, like the labels along a 45° line""" 76 # The lines of characters drop the spaces, every character on a slanted line is a line of its own 77 spaces = [c for c in self._page.chars_in_area(self.bbox) if 1 < c.rotation % 90 < 89 and c.unicode == 0x20] 78 chars = list({(c._index, c.unicode): c for c in chars + spaces}.values()) 79 runs = [] 80 for char in chars: 81 m = pp.raw.FS_MATRIX() 82 pp.raw.FPDFText_GetMatrix(char._text, char._index, m) 83 scale = math.hypot(m.a, m.b) 84 # The font size is split between the text matrix and the font 85 size = math.sqrt(abs(m.a * m.d - m.b * m.c)) * char.size 86 if not scale or not size: 87 continue 88 ux, uy = m.a / scale, m.b / scale 89 along = char.origin.x * ux + char.origin.y * uy 90 normal = char.origin.y * ux - char.origin.x * uy 91 runs.append((char.font, round(math.degrees(math.atan2(uy, ux))), normal, along, size, char)) 92 # Characters on the same baseline are one line, split into texts at gaps 93 groups = [] 94 runs.sort(key=lambda r: (r[0], r[1], r[2])) 95 lines = [] 96 for run in runs: 97 last = lines[-1][-1] if lines else None 98 if last and last[:2] == run[:2] and run[2] - last[2] < 0.2 * run[4]: 99 lines[-1].append(run) 100 else: 101 lines.append([run]) 102 for line in lines: 103 line.sort(key=lambda r: r[3]) 104 for font, angle, _, along, size, char in line: 105 if groups and groups[-1]["line"] is line and along - groups[-1]["along"] < 1.5 * size: 106 groups[-1]["chars"].append(char) 107 else: 108 groups.append({"line": line, "key": (font, angle), "chars": [char], "size": size}) 109 groups[-1]["along"] = along 110 for group in groups: 111 (font, angle), chars = group["key"], group["chars"] 112 text = "".join(c.char for c in chars) 113 if not text.strip(): 114 continue 115 node = etree.Element("text") 116 node.text = text.strip() 117 node.set("font-size", _n(group["size"])) 118 if "Bold" in font: 119 node.set("font-weight", "bold") 120 if "Italic" in font or "Oblique" in font: 121 node.set("font-style", "italic") 122 first = next(c for c in chars if c.char.strip()) 123 if first.fill != 0xFF: 124 _color(node, "fill", first.fill) 125 node.set("transform", f"translate({self._xy(first.origin)}) rotate({-angle})") 126 yield node 127 128 def _svg_texts(self): 129 slanted = [] 130 for line in self._page.charlines_in_area(self.bbox): 131 horizontal = not line.rotation 132 # Split the line into runs of the same font, size and baseline, and 133 # at gaps, since labels in figures are unrelated to each other 134 runs, last = [], None 135 for char in line.chars: 136 if 1 < char.rotation % 90 < 89: 137 slanted.append(char) 138 continue 139 if horizontal: 140 baseline, start, stop = char.origin.y, char.bbox.left, char.bbox.right 141 elif line.rotation == 90: 142 baseline, start, stop = char.origin.x, char.bbox.bottom, char.bbox.top 143 else: 144 baseline, start, stop = char.origin.x, -char.bbox.top, -char.bbox.bottom 145 key = (char.font, round(char.height, 1), round(baseline, 1)) 146 if char.unicode in {0x20, 0xA, 0xD}: 147 # Whitespace has no reliable position, it continues the run 148 if runs: 149 runs[-1][1].append(char) 150 continue 151 if not runs or runs[-1][0] != key or start - last > 0.5 * line.height: 152 runs.append((key, [])) 153 runs[-1][1].append(char) 154 last = stop 155 156 for (font, size, _), chars in runs: 157 while chars and not chars[-1].char.strip(): 158 chars = chars[:-1] 159 if not chars or not size: 160 continue 161 node = etree.Element("text") 162 node.text = "".join(c.char for c in chars) 163 node.set("font-size", _n(size)) 164 if "Bold" in font: 165 node.set("font-weight", "bold") 166 if "Italic" in font or "Oblique" in font: 167 node.set("font-style", "italic") 168 if chars[0].fill != 0xFF: 169 _color(node, "fill", chars[0].fill) 170 xy = self._xy(chars[0].origin) 171 if horizontal: 172 length = chars[-1].bbox.right - chars[0].bbox.left 173 node.set("x", xy.split()[0]) 174 node.set("y", xy.split()[1]) 175 else: 176 length = chars[-1].bbox.top - chars[0].bbox.bottom 177 angle = -90 if line.rotation == 90 else 90 178 node.set("transform", f"translate({xy}) rotate({angle})") 179 # Keeps the layout intact when rendered with another font 180 if len(chars) > 1 and length > 0: 181 node.set("textLength", _n(abs(length))) 182 # Condensed text squeezes the glyphs, not only the space between them, otherwise they overlap 183 m = pp.raw.FS_MATRIX() 184 pp.raw.FPDFText_GetMatrix(chars[0]._text, chars[0]._index, m) 185 if math.hypot(m.a, m.b) < 0.9 * math.hypot(m.c, m.d): 186 node.set("lengthAdjust", "spacingAndGlyphs") 187 yield node 188 yield from self._svg_slanted_texts(slanted) 189 190 def _in_bbox(self, objects: list) -> list: 191 box = self.bbox 192 return [ 193 o 194 for o in objects 195 if o.bbox.left < box.right 196 and box.left < o.bbox.right 197 and o.bbox.bottom < box.top 198 and box.bottom < o.bbox.top 199 ] 200 201 @property 202 def images(self) -> list[Image]: 203 """The bitmap images of the figure.""" 204 return self._in_bbox(self._page.images) 205 206 def _svg_image(self, image: Image, href: str): 207 node = etree.Element("image", href=href, preserveAspectRatio="none") 208 m = image.matrix.get() 209 # Images in forms have a matrix relative to the form, then we only know their bounds 210 xs = [m[4], m[4] + m[0], m[4] + m[2], m[4] + m[0] + m[2]] 211 ys = [m[5], m[5] + m[1], m[5] + m[3], m[5] + m[1] + m[3]] 212 matching = Rectangle(min(xs), min(ys), max(xs), max(ys)).isclose(image.bbox, atol=0.5) 213 if self._page.rotation or not matching: 214 x, y = self._xy(Point(image.bbox.left, image.bbox.top)).split() 215 node.set("x", x) 216 node.set("y", y) 217 node.set("width", _n(image.bbox.width)) 218 node.set("height", _n(image.bbox.height)) 219 else: 220 # The image matrix maps the unit square to the page and may flip or 221 # rotate the image, its top row is at y=1, while SVG starts at y=0 222 a, b, c, d, e, f = m 223 node.set("width", "1") 224 node.set("height", "1") 225 matrix = (a, -b, -c, d, c + e - self.bbox.left, self.bbox.top - d - f) 226 node.set("transform", f"matrix({' '.join(f'{v:.4f}'.rstrip('0').rstrip('.') for v in matrix)})") 227 return node 228 229 def as_svg(self, image_hrefs: list[str] = None) -> etree._Element | None: 230 """ 231 :param image_hrefs: The file names of the saved `images`, which are 232 then referenced by the SVG at their position. 233 :return: The vector graphics and text of the figure as SVG, or `None` 234 if the figure has neither, for example, for bitmap images. 235 """ 236 paths = [p for p in self._in_bbox(self._page.paths) if p.count > 1 and any(p.draw_mode)] 237 texts = list(self._svg_texts()) 238 if not paths and not texts: 239 return None 240 241 # Paths and images are drawn in the order of the page, since a filled 242 # path may be the background of an image or cover parts of it 243 order = {ctypes.cast(o.raw, ctypes.c_void_p).value: i for i, o in enumerate(self._page.get_objects())} 244 graphics = [(p, self._svg_path(p)) for p in paths] 245 graphics += [(i, self._svg_image(i, h)) for i, h in zip(self.images, image_hrefs or [])] 246 graphics.sort(key=lambda g: order.get(ctypes.cast(g[0].raw, ctypes.c_void_p).value, -1)) 247 nodes = [node for _, node in graphics] + texts 248 249 svg = etree.Element("svg", xmlns="http://www.w3.org/2000/svg") 250 svg.set("viewBox", f"0 0 {_n(self.bbox.width)} {_n(self.bbox.height)}") 251 # In points like the text of the HTML, so that the figures keep their size relative to the text 252 svg.set("width", f"{_n(self.bbox.width)}pt") 253 svg.set("height", f"{_n(self.bbox.height)}pt") 254 svg.set("font-family", "Arial, Helvetica, sans-serif") 255 svg.extend(nodes) 256 return svg 257 258 def __repr__(self) -> str: 259 return f"Figure({int(self.bbox.width)}x{int(self.bbox.height)})"
class
Figure:
27class Figure: 28 def __init__(self, page, bbox: Rectangle, cbbox: Rectangle = None, paths: list = None): 29 self._page = page 30 self.bbox = bbox 31 self.cbbox = cbbox 32 self._type = "figure" 33 self._paths = paths or [] 34 35 def _xy(self, point) -> str: 36 # PDF has its origin in the bottom left corner, SVG in the top left 37 return f"{_n(point.x - self.bbox.left)} {_n(self.bbox.top - point.y)}" 38 39 def _svg_path(self, path: Path): 40 data, curve = [], [] 41 for point in path.points: 42 if point.type == Path.Type.BEZIER: 43 # Cubic curves consist of two control points and the end point 44 curve.append(self._xy(point)) 45 if len(curve) == 3: 46 data.append("C" + " ".join(curve)) 47 curve = [] 48 else: 49 data.append(("M" if point.type == Path.Type.MOVE else "L") + self._xy(point)) 50 node = etree.Element("path", d="".join(data)) 51 52 fill_mode, stroked = path.draw_mode 53 if fill_mode: 54 _color(node, "fill", path.fill) 55 if fill_mode == 1: 56 node.set("fill-rule", "evenodd") 57 else: 58 node.set("fill", "none") 59 if stroked: 60 _color(node, "stroke", path.stroke) 61 # The stroke width is not part of the path and must be scaled 62 m = path.matrix.get() 63 scale = math.sqrt(abs(m[0] * m[3] - m[1] * m[2])) 64 # PDF viewers draw strokes at least one device pixel wide, so that 65 # hairlines stay visible, which SVG renderers do not do 66 node.set("stroke-width", _n(max(path.width * scale, _HAIRLINE))) 67 if path.dashes: 68 node.set("stroke-dasharray", " ".join(_n(d * scale) for d in path.dashes)) 69 if path.cap != Path.Cap.BUTT: 70 node.set("stroke-linecap", "round" if path.cap == Path.Cap.ROUND else "square") 71 if path.join != Path.Join.MITER: 72 node.set("stroke-linejoin", path.join.name.lower()) 73 return node 74 75 def _svg_slanted_texts(self, chars): 76 """Text at an angle that is no multiple of 90°, like the labels along a 45° line""" 77 # The lines of characters drop the spaces, every character on a slanted line is a line of its own 78 spaces = [c for c in self._page.chars_in_area(self.bbox) if 1 < c.rotation % 90 < 89 and c.unicode == 0x20] 79 chars = list({(c._index, c.unicode): c for c in chars + spaces}.values()) 80 runs = [] 81 for char in chars: 82 m = pp.raw.FS_MATRIX() 83 pp.raw.FPDFText_GetMatrix(char._text, char._index, m) 84 scale = math.hypot(m.a, m.b) 85 # The font size is split between the text matrix and the font 86 size = math.sqrt(abs(m.a * m.d - m.b * m.c)) * char.size 87 if not scale or not size: 88 continue 89 ux, uy = m.a / scale, m.b / scale 90 along = char.origin.x * ux + char.origin.y * uy 91 normal = char.origin.y * ux - char.origin.x * uy 92 runs.append((char.font, round(math.degrees(math.atan2(uy, ux))), normal, along, size, char)) 93 # Characters on the same baseline are one line, split into texts at gaps 94 groups = [] 95 runs.sort(key=lambda r: (r[0], r[1], r[2])) 96 lines = [] 97 for run in runs: 98 last = lines[-1][-1] if lines else None 99 if last and last[:2] == run[:2] and run[2] - last[2] < 0.2 * run[4]: 100 lines[-1].append(run) 101 else: 102 lines.append([run]) 103 for line in lines: 104 line.sort(key=lambda r: r[3]) 105 for font, angle, _, along, size, char in line: 106 if groups and groups[-1]["line"] is line and along - groups[-1]["along"] < 1.5 * size: 107 groups[-1]["chars"].append(char) 108 else: 109 groups.append({"line": line, "key": (font, angle), "chars": [char], "size": size}) 110 groups[-1]["along"] = along 111 for group in groups: 112 (font, angle), chars = group["key"], group["chars"] 113 text = "".join(c.char for c in chars) 114 if not text.strip(): 115 continue 116 node = etree.Element("text") 117 node.text = text.strip() 118 node.set("font-size", _n(group["size"])) 119 if "Bold" in font: 120 node.set("font-weight", "bold") 121 if "Italic" in font or "Oblique" in font: 122 node.set("font-style", "italic") 123 first = next(c for c in chars if c.char.strip()) 124 if first.fill != 0xFF: 125 _color(node, "fill", first.fill) 126 node.set("transform", f"translate({self._xy(first.origin)}) rotate({-angle})") 127 yield node 128 129 def _svg_texts(self): 130 slanted = [] 131 for line in self._page.charlines_in_area(self.bbox): 132 horizontal = not line.rotation 133 # Split the line into runs of the same font, size and baseline, and 134 # at gaps, since labels in figures are unrelated to each other 135 runs, last = [], None 136 for char in line.chars: 137 if 1 < char.rotation % 90 < 89: 138 slanted.append(char) 139 continue 140 if horizontal: 141 baseline, start, stop = char.origin.y, char.bbox.left, char.bbox.right 142 elif line.rotation == 90: 143 baseline, start, stop = char.origin.x, char.bbox.bottom, char.bbox.top 144 else: 145 baseline, start, stop = char.origin.x, -char.bbox.top, -char.bbox.bottom 146 key = (char.font, round(char.height, 1), round(baseline, 1)) 147 if char.unicode in {0x20, 0xA, 0xD}: 148 # Whitespace has no reliable position, it continues the run 149 if runs: 150 runs[-1][1].append(char) 151 continue 152 if not runs or runs[-1][0] != key or start - last > 0.5 * line.height: 153 runs.append((key, [])) 154 runs[-1][1].append(char) 155 last = stop 156 157 for (font, size, _), chars in runs: 158 while chars and not chars[-1].char.strip(): 159 chars = chars[:-1] 160 if not chars or not size: 161 continue 162 node = etree.Element("text") 163 node.text = "".join(c.char for c in chars) 164 node.set("font-size", _n(size)) 165 if "Bold" in font: 166 node.set("font-weight", "bold") 167 if "Italic" in font or "Oblique" in font: 168 node.set("font-style", "italic") 169 if chars[0].fill != 0xFF: 170 _color(node, "fill", chars[0].fill) 171 xy = self._xy(chars[0].origin) 172 if horizontal: 173 length = chars[-1].bbox.right - chars[0].bbox.left 174 node.set("x", xy.split()[0]) 175 node.set("y", xy.split()[1]) 176 else: 177 length = chars[-1].bbox.top - chars[0].bbox.bottom 178 angle = -90 if line.rotation == 90 else 90 179 node.set("transform", f"translate({xy}) rotate({angle})") 180 # Keeps the layout intact when rendered with another font 181 if len(chars) > 1 and length > 0: 182 node.set("textLength", _n(abs(length))) 183 # Condensed text squeezes the glyphs, not only the space between them, otherwise they overlap 184 m = pp.raw.FS_MATRIX() 185 pp.raw.FPDFText_GetMatrix(chars[0]._text, chars[0]._index, m) 186 if math.hypot(m.a, m.b) < 0.9 * math.hypot(m.c, m.d): 187 node.set("lengthAdjust", "spacingAndGlyphs") 188 yield node 189 yield from self._svg_slanted_texts(slanted) 190 191 def _in_bbox(self, objects: list) -> list: 192 box = self.bbox 193 return [ 194 o 195 for o in objects 196 if o.bbox.left < box.right 197 and box.left < o.bbox.right 198 and o.bbox.bottom < box.top 199 and box.bottom < o.bbox.top 200 ] 201 202 @property 203 def images(self) -> list[Image]: 204 """The bitmap images of the figure.""" 205 return self._in_bbox(self._page.images) 206 207 def _svg_image(self, image: Image, href: str): 208 node = etree.Element("image", href=href, preserveAspectRatio="none") 209 m = image.matrix.get() 210 # Images in forms have a matrix relative to the form, then we only know their bounds 211 xs = [m[4], m[4] + m[0], m[4] + m[2], m[4] + m[0] + m[2]] 212 ys = [m[5], m[5] + m[1], m[5] + m[3], m[5] + m[1] + m[3]] 213 matching = Rectangle(min(xs), min(ys), max(xs), max(ys)).isclose(image.bbox, atol=0.5) 214 if self._page.rotation or not matching: 215 x, y = self._xy(Point(image.bbox.left, image.bbox.top)).split() 216 node.set("x", x) 217 node.set("y", y) 218 node.set("width", _n(image.bbox.width)) 219 node.set("height", _n(image.bbox.height)) 220 else: 221 # The image matrix maps the unit square to the page and may flip or 222 # rotate the image, its top row is at y=1, while SVG starts at y=0 223 a, b, c, d, e, f = m 224 node.set("width", "1") 225 node.set("height", "1") 226 matrix = (a, -b, -c, d, c + e - self.bbox.left, self.bbox.top - d - f) 227 node.set("transform", f"matrix({' '.join(f'{v:.4f}'.rstrip('0').rstrip('.') for v in matrix)})") 228 return node 229 230 def as_svg(self, image_hrefs: list[str] = None) -> etree._Element | None: 231 """ 232 :param image_hrefs: The file names of the saved `images`, which are 233 then referenced by the SVG at their position. 234 :return: The vector graphics and text of the figure as SVG, or `None` 235 if the figure has neither, for example, for bitmap images. 236 """ 237 paths = [p for p in self._in_bbox(self._page.paths) if p.count > 1 and any(p.draw_mode)] 238 texts = list(self._svg_texts()) 239 if not paths and not texts: 240 return None 241 242 # Paths and images are drawn in the order of the page, since a filled 243 # path may be the background of an image or cover parts of it 244 order = {ctypes.cast(o.raw, ctypes.c_void_p).value: i for i, o in enumerate(self._page.get_objects())} 245 graphics = [(p, self._svg_path(p)) for p in paths] 246 graphics += [(i, self._svg_image(i, h)) for i, h in zip(self.images, image_hrefs or [])] 247 graphics.sort(key=lambda g: order.get(ctypes.cast(g[0].raw, ctypes.c_void_p).value, -1)) 248 nodes = [node for _, node in graphics] + texts 249 250 svg = etree.Element("svg", xmlns="http://www.w3.org/2000/svg") 251 svg.set("viewBox", f"0 0 {_n(self.bbox.width)} {_n(self.bbox.height)}") 252 # In points like the text of the HTML, so that the figures keep their size relative to the text 253 svg.set("width", f"{_n(self.bbox.width)}pt") 254 svg.set("height", f"{_n(self.bbox.height)}pt") 255 svg.set("font-family", "Arial, Helvetica, sans-serif") 256 svg.extend(nodes) 257 return svg 258 259 def __repr__(self) -> str: 260 return f"Figure({int(self.bbox.width)}x{int(self.bbox.height)})"
Figure( page, bbox: modm_data.utils.Rectangle, cbbox: modm_data.utils.Rectangle = None, paths: list = None)
images: list[modm_data.pdf.Image]
202 @property 203 def images(self) -> list[Image]: 204 """The bitmap images of the figure.""" 205 return self._in_bbox(self._page.images)
The bitmap images of the figure.
def
as_svg(self, image_hrefs: list[str] = None) -> lxml.etree._Element | None:
230 def as_svg(self, image_hrefs: list[str] = None) -> etree._Element | None: 231 """ 232 :param image_hrefs: The file names of the saved `images`, which are 233 then referenced by the SVG at their position. 234 :return: The vector graphics and text of the figure as SVG, or `None` 235 if the figure has neither, for example, for bitmap images. 236 """ 237 paths = [p for p in self._in_bbox(self._page.paths) if p.count > 1 and any(p.draw_mode)] 238 texts = list(self._svg_texts()) 239 if not paths and not texts: 240 return None 241 242 # Paths and images are drawn in the order of the page, since a filled 243 # path may be the background of an image or cover parts of it 244 order = {ctypes.cast(o.raw, ctypes.c_void_p).value: i for i, o in enumerate(self._page.get_objects())} 245 graphics = [(p, self._svg_path(p)) for p in paths] 246 graphics += [(i, self._svg_image(i, h)) for i, h in zip(self.images, image_hrefs or [])] 247 graphics.sort(key=lambda g: order.get(ctypes.cast(g[0].raw, ctypes.c_void_p).value, -1)) 248 nodes = [node for _, node in graphics] + texts 249 250 svg = etree.Element("svg", xmlns="http://www.w3.org/2000/svg") 251 svg.set("viewBox", f"0 0 {_n(self.bbox.width)} {_n(self.bbox.height)}") 252 # In points like the text of the HTML, so that the figures keep their size relative to the text 253 svg.set("width", f"{_n(self.bbox.width)}pt") 254 svg.set("height", f"{_n(self.bbox.height)}pt") 255 svg.set("font-family", "Arial, Helvetica, sans-serif") 256 svg.extend(nodes) 257 return svg
Parameters
- image_hrefs: The file names of the saved
images, which are then referenced by the SVG at their position.
Returns
The vector graphics and text of the figure as SVG, or
Noneif the figure has neither, for example, for bitmap images.