#!/usr/bin/env python3 """ Export a Player PDF from a DM SVG card. Removes: - Price tag rectangle and price text - "DUNGEON MASTER'S COPY" text elements - Bottom red bars (DM indicator) Writes a temporary modified SVG, exports via Inkscape, then cleans up. """ import argparse import os import re import subprocess import sys import tempfile import xml.etree.ElementTree as ET from pathlib import Path SVG_NS = "http://www.w3.org/2000/svg" XLINK_NS = "http://www.w3.org/1999/xlink" INKSCAPE_NS = "http://www.inkscape.org/namespaces/inkscape" SODIPODI_NS = "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" ET.register_namespace("", SVG_NS) ET.register_namespace("svg", SVG_NS) ET.register_namespace("inkscape", INKSCAPE_NS) ET.register_namespace("sodipodi", SODIPODI_NS) ET.register_namespace("xlink", XLINK_NS) def strip_dm_elements(svg_path, tmp_svg_path): """Create a player version of the SVG with DM elements removed.""" tree = ET.parse(svg_path) root = tree.getroot() layer = root.find(f".//{{{SVG_NS}}}g[@id='layer1']") if layer is None: for g in root.iter(f"{{{SVG_NS}}}g"): if g.get(f"{{{INKSCAPE_NS}}}groupmode") == "layer": layer = g break if layer is None: print("ERROR: Could not find layer1", file=sys.stderr) sys.exit(1) to_remove = [] for child in layer: tag = child.tag.split("}")[-1] if "}" in child.tag else child.tag style = child.get("style", "") transform = child.get("transform", "") if tag == "text": tspans = child.findall(f"{{{SVG_NS}}}tspan") first_text = "" for ts in tspans: if ts.text: first_text = ts.text break if "DUNGEON MASTER" in first_text: to_remove.append(child) elif "rotate" in transform: to_remove.append(child) elif tag == "rect": fill_m = re.search(r"fill:([^;]+)", style) fill = fill_m.group(1) if fill_m else "" w = float(child.get("width", "0")) h = float(child.get("height", "0")) ry = child.get("ry", "") if "d40000" in fill and "rotate" in transform: to_remove.append(child) elif w > 5 and h > 15 and "url(" not in fill: ry_val = float(ry) if ry else 0 if ry_val > 0.3 and ry_val < 2: to_remove.append(child) for elem in to_remove: layer.remove(elem) SCALE = 0.26458333 RECT_Y_SCALED = 84.18 * SCALE LINE_HEIGHT_MM = 3.1 DM_BAR_Y = 80.1 CARD_BOTTOM = 85.6 SIDE_MARGIN = 4.3 IMAGE_TEXT_GAP = 3.0 TITLE_BOTTOM = 14.0 front_text_elem = None image_elem = None for child in layer: tag = child.tag.split("}")[-1] if "}" in child.tag else child.tag style = child.get("style", "") transform = child.get("transform", "") if tag == "text" and "shape-inside" in style and "matrix" in transform: x_off_m = re.search(r"matrix\([^,]+,[^,]+,[^,]+,[^,]+,([^,]+)", transform) if x_off_m and float(x_off_m.group(1)) < 50: front_text_elem = child if tag == "image": image_elem = child if front_text_elem is not None: tspans = front_text_elem.findall(f"{{{SVG_NS}}}tspan") plain_text = "" for ts in tspans: if ts.text: plain_text += ts.text for inner in ts: if inner.text: plain_text += inner.text if inner.tail: plain_text += inner.tail parts = re.split(r"(\*\*[^*]+\*\*|\*[^*]+\*)", plain_text.strip()) words_with_width = [] for part in parts: if not part: continue is_bold = part.startswith("**") and part.endswith("**") clean = re.sub(r"\*+", "", part) for w in clean.split(): effective_len = len(w) * 1.05 if is_bold else len(w) words_with_width.append(effective_len) n_lines = 1 col = 0.0 for w_len in words_with_width: needed = w_len + (1 if col > 0 else 0) if col + needed > 42: n_lines += 1 col = w_len else: col += needed text_height = n_lines * LINE_HEIGHT_MM text_end = CARD_BOTTOM - SIDE_MARGIN text_start = text_end - text_height y_offset = text_start - RECT_Y_SCALED transform = front_text_elem.get("transform", "") transform = re.sub( r"(matrix\([^,]+,[^,]+,[^,]+,[^,]+,[^,]+,)([^)]+)\)", rf"\g<1>{y_offset})", transform, ) front_text_elem.set("transform", transform) if image_elem is not None and front_text_elem is not None: is_two_line = False for t in layer: tag_t = t.tag.split("}")[-1] if "}" in t.tag else t.tag if tag_t == "g": for sub in t: if sub.get("id", "") == "text18": tspans_t = sub.findall(f"{{{SVG_NS}}}tspan") if len(tspans_t) >= 2: is_two_line = True if tag_t == "text" and t.get("id", "") == "text18": tspans_t = t.findall(f"{{{SVG_NS}}}tspan") if len(tspans_t) >= 2: is_two_line = True title_bottom = 19.0 if is_two_line else TITLE_BOTTOM img_size = 53.0 if is_two_line else 58.0 IMAGE_BUFFER = 5.0 old_w = float(image_elem.get("width", "65")) old_h = float(image_elem.get("height", "65")) avail = text_start - title_bottom effective_size = min(img_size, avail - IMAGE_BUFFER) effective_size = max(effective_size, 30.0) scale = effective_size / max(old_w, old_h) new_w = old_w * scale new_h = old_h * scale image_elem.set("width", str(new_w)) image_elem.set("height", str(new_h)) img_y = title_bottom + (avail - new_h) / 2 card_width = 53.98 img_x = (card_width - new_w) / 2 image_elem.set("y", str(img_y)) image_elem.set("x", str(img_x)) tree.write(tmp_svg_path, xml_declaration=True, encoding="unicode") return tmp_svg_path def export_pdf(svg_path, output_pdf): """Export SVG to 2-page PDF via Inkscape.""" with tempfile.TemporaryDirectory() as tmpdir: base = os.path.join(tmpdir, "page") subprocess.run( [ "inkscape", svg_path, "--export-type=pdf", f"--export-filename={base}", "--export-page=all", ], capture_output=True, text=True, ) p1 = f"{base}_p1.pdf" p2 = f"{base}_p2.pdf" if os.path.exists(p1) and os.path.exists(p2): subprocess.run( ["pdfunite", p1, p2, output_pdf], capture_output=True, text=True, ) print(f"Exported: {output_pdf}") elif os.path.exists(p1): import shutil shutil.copy2(p1, output_pdf) print(f"Exported (single page): {output_pdf}") else: print(f"ERROR: Inkscape export failed for {svg_path}", file=sys.stderr) sys.exit(1) def main(): parser = argparse.ArgumentParser(description="Export player PDF from DM SVG") parser.add_argument("svg", help="Input SVG (DM version)") parser.add_argument("-o", "--output", required=True, help="Output PDF path") args = parser.parse_args() with tempfile.NamedTemporaryFile(suffix=".svg", delete=False) as tmp: tmp_svg = tmp.name try: strip_dm_elements(args.svg, tmp_svg) export_pdf(tmp_svg, args.output) finally: if os.path.exists(tmp_svg): os.unlink(tmp_svg) if __name__ == "__main__": main()