Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(pptx-to-svg): respect break and empty paragraph line heights

hugohe3ce7681d38921
diff --git a/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py
index e613911e..9181c682 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py
@@ -75,6 +75,7 @@ class TextParagraph:
line_height_ratio: float = DEFAULT_LINE_HEIGHT_RATIO
space_before_px: float = 0.0
space_after_px: float = 0.0
+ empty_line_font_size_px: float = DEFAULT_FONT_SIZE_PX
bullet_prefix: str = "" # rendered prefix like '• ' or '1. '
@@ -412,6 +413,21 @@ def _parse_paragraph(
# defRPr from pPr and txBody/lstStyle, both optional.
def_rpr = p_pr.find("a:defRPr", NS) if p_pr is not None else None
list_def_rpr = _child_chain(para_style_chain[1:], "a:defRPr")
+ para.empty_line_font_size_px = _font_size_px(
+ (end_rpr, def_rpr, list_def_rpr) + fallback_run_props,
+ default_font_size_px,
+ )
+
+ def resolved_run(text: str, rpr: ET.Element | None) -> TextRun:
+ return _build_run(
+ text, rpr, end_rpr, palette, theme_fonts,
+ def_rpr=def_rpr,
+ list_def_rpr=list_def_rpr,
+ fallback_run_props=fallback_run_props,
+ default_fill=default_fill,
+ default_font_size_px=default_font_size_px,
+ id_prefix=id_prefix, id_seq=id_seq,
+ )
for child in list(p_elem):
if not isinstance(child.tag, str):
@@ -421,21 +437,18 @@ def _parse_paragraph(
rpr = child.find("a:rPr", NS)
text_elem = child.find("a:t", NS)
text = text_elem.text or "" if text_elem is not None else ""
- run = _build_run(
- text, rpr, end_rpr, palette, theme_fonts,
- def_rpr=def_rpr,
- list_def_rpr=list_def_rpr,
- fallback_run_props=fallback_run_props,
- default_fill=default_fill,
- default_font_size_px=default_font_size_px,
- id_prefix=id_prefix, id_seq=id_seq,
- )
- para.runs.append(run)
+ para.runs.append(resolved_run(text, rpr))
elif local == "br":
+ break_rpr = child.find("a:rPr", NS)
para.runs.append(TextRun(
text="",
- font_size_px=default_font_size_px,
- font_family="sans-serif", fill=default_fill,
+ font_size_px=_font_size_px(
+ (break_rpr, def_rpr, list_def_rpr, end_rpr)
+ + fallback_run_props,
+ default_font_size_px,
+ ),
+ font_family="sans-serif",
+ fill=default_fill,
is_break=True,
))
elif local == "fld":
@@ -449,20 +462,22 @@ def _parse_paragraph(
if field_type == "slidenum" and slide_number is not None:
text = str(slide_number)
if text:
- run = _build_run(
- text, rpr, end_rpr, palette, theme_fonts,
- def_rpr=def_rpr,
- list_def_rpr=list_def_rpr,
- fallback_run_props=fallback_run_props,
- default_fill=default_fill,
- default_font_size_px=default_font_size_px,
- id_prefix=id_prefix, id_seq=id_seq,
- )
- para.runs.append(run)
+ para.runs.append(resolved_run(text, rpr))
return para
+def _font_size_px(
+ sources: tuple[ET.Element | None, ...],
+ default_font_size_px: float,
+) -> float:
+ """Resolve one effective DrawingML run size into SVG pixels."""
+ return hundredths_pt_to_px(
+ _attr_chain(sources, "sz"),
+ default_font_size_px,
+ )
+
+
def _build_run(
text: str,
rpr: ET.Element | None,
@@ -483,8 +498,7 @@ def _build_run(
rpr, def_rpr, list_def_rpr, end_rpr,
) + fallback_run_props
# font-size: rPr > pPr/defRPr > lstStyle/lvlNpPr/defRPr > endParaRPr > default
- sz = _attr_chain(style_chain, "sz")
- font_size_px = hundredths_pt_to_px(sz, default_font_size_px)
+ font_size_px = _font_size_px(style_chain, default_font_size_px)
# Bold / italic
bold = _attr_chain(style_chain, "b") == "1"
italic = _attr_chain(style_chain, "i") == "1"
@@ -916,6 +930,10 @@ def _wrap_paragraph_into_lines(
for run in para.runs:
if run.is_break:
+ # Keep the break on the line it terminates so consecutive breaks
+ # form a break-only empty line. Visible text owns a non-empty
+ # line's height; the break rPr owns only that empty line.
+ lines[-1].append(run)
lines.append([])
cur_w = 0.0
continue
@@ -997,7 +1015,7 @@ def _paragraph_height_from_lines(p: TextParagraph,
lines: list[list[TextRun]]) -> float:
"""Total px height after wrapping. Each line uses its own max font size."""
if not lines:
- return DEFAULT_FONT_SIZE_PX * p.line_height_ratio
+ return p.empty_line_font_size_px * p.line_height_ratio
height = 0.0
for line in lines:
height += _line_height(p, line)
@@ -1005,8 +1023,19 @@ def _paragraph_height_from_lines(p: TextParagraph,
def _line_height(p: TextParagraph, line: list[TextRun]) -> float:
- max_font = max((r.font_size_px for r in line), default=DEFAULT_FONT_SIZE_PX)
- return max_font * p.line_height_ratio
+ return _line_font_size(p, line) * p.line_height_ratio
+
+
+def _line_font_size(p: TextParagraph, line: list[TextRun]) -> float:
+ visible_sizes = [
+ run.font_size_px
+ for run in line
+ if not run.is_break and run.text
+ ]
+ if visible_sizes:
+ return max(visible_sizes)
+ break_sizes = [run.font_size_px for run in line if run.is_break]
+ return max(break_sizes, default=p.empty_line_font_size_px)
def _clip_lines_to_bottom(
@@ -1032,16 +1061,8 @@ def _clip_lines_to_bottom(
def _paragraph_height(p: TextParagraph) -> float:
"""Legacy helper kept for callers that don't pre-wrap (currently unused)."""
- lines = 1
- max_font = 0.0
- for r in p.runs:
- if r.is_break:
- lines += 1
- continue
- max_font = max(max_font, r.font_size_px)
- if max_font == 0.0:
- max_font = DEFAULT_FONT_SIZE_PX
- return lines * max_font * p.line_height_ratio
+ lines = _wrap_paragraph_into_lines(p, float("inf"))
+ return _paragraph_height_from_lines(p, lines)
def _emit_paragraph(
@@ -1067,33 +1088,45 @@ def _emit_paragraph(
anchor_x = inner_x + para.indent_px + para.margin_left_px
text_anchor = "start"
- if not lines or all(not line for line in lines):
+ if not lines:
return ""
- # First non-empty line drives the text-level baseline + default style
- first_line_idx = next((i for i, ln in enumerate(lines) if ln), 0)
- first_line = lines[first_line_idx]
- first_run = first_line[0] if first_line else None
- first_font = first_run.font_size_px if first_run else DEFAULT_FONT_SIZE_PX
- first_baseline = top_y + 0.85 * first_font
+ visible_lines = [
+ [run for run in line if not run.is_break and run.text]
+ for line in lines
+ ]
+ first_line_idx = next(
+ (index for index, line in enumerate(visible_lines) if line),
+ None,
+ )
+ if first_line_idx is None:
+ return ""
+
+ first_run = visible_lines[first_line_idx][0]
+ first_baseline = top_y + 0.85 * first_run.font_size_px
spans: list[str] = []
- for line_idx, line in enumerate(lines):
- if not line:
- # Blank line (e.g. consecutive a:br): still advance baseline
- spans.append(
- f'<tspan x="{fmt_num(anchor_x)}" '
- f'dy="{fmt_num(first_font * para.line_height_ratio)}"></tspan>'
+ for line_idx, line in enumerate(visible_lines):
+ line_advance = None
+ if line_idx > 0:
+ height_line = (
+ lines[line_idx - 1]
+ if line_idx <= first_line_idx else lines[line_idx]
)
+ line_advance = _line_height(para, height_line)
+ if not line:
+ if line_advance is not None:
+ spans.append(
+ f'<tspan x="{fmt_num(anchor_x)}" '
+ f'dy="{fmt_num(line_advance)}"></tspan>'
+ )
continue
- line_font = max(r.font_size_px for r in line)
for run_idx, run in enumerate(line):
attrs = _run_tspan_attrs(run)
- if run_idx == 0 and line_idx > 0:
- # Start-of-line tspan: position via x + dy
+ if run_idx == 0 and line_advance is not None:
spans.append(
f'<tspan x="{fmt_num(anchor_x)}" '
- f'dy="{fmt_num(line_font * para.line_height_ratio)}"'
+ f'dy="{fmt_num(line_advance)}"'
f'{attrs}>{_xml_escape(run.text)}</tspan>'
)
else:
diff --git a/skills/ppt-master/scripts/test_svg_quality_checker.py b/skills/ppt-master/scripts/test_svg_quality_checker.py
index e8f5f78c..965771b6 100644
--- a/skills/ppt-master/scripts/test_svg_quality_checker.py
+++ b/skills/ppt-master/scripts/test_svg_quality_checker.py
@@ -30,7 +30,7 @@ from pptx_to_svg.preset_authoring import (
validate_authored_preset_tree,
)
from pptx_to_svg.emu_units import Xfrm
-from pptx_to_svg.txbody_to_svg import convert_vertical_txbody
+from pptx_to_svg.txbody_to_svg import convert_txbody, convert_vertical_txbody
from svg_to_pptx.animation_config import (
build_group_listing,
build_scaffold,
@@ -115,6 +115,40 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):
)
return base64.b64encode(native_txbody.encode('utf-8')).decode('ascii')
+ @staticmethod
+ def _txbody_preview(paragraphs: str) -> str:
+ tx_body = ET.fromstring(f'''
+<p:txBody xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"
+ xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
+ <a:bodyPr anchor="t" wrap="none" lIns="0" rIns="0" tIns="0" bIns="0"/>
+ <a:lstStyle/>{paragraphs}
+</p:txBody>''')
+ return convert_txbody(
+ tx_body,
+ Xfrm(x=20, y=20, w=500, h=300),
+ None,
+ ).svg
+
+ @staticmethod
+ def _visible_text_baselines(svg_fragment: str) -> dict[str, list[float]]:
+ root = ET.fromstring(
+ '<svg xmlns="http://www.w3.org/2000/svg">'
+ f'{svg_fragment}</svg>'
+ )
+ baselines: dict[str, list[float]] = {}
+ namespace = '{http://www.w3.org/2000/svg}'
+ for text in root.iter(f'{namespace}text'):
+ cursor_y = float(text.get('y') or '0')
+ for span in text.findall(f'{namespace}tspan'):
+ if span.get('y') is not None:
+ cursor_y = float(span.get('y') or '0')
+ if span.get('dy') is not None:
+ cursor_y += float(span.get('dy') or '0')
+ value = ''.join(span.itertext())
+ if value:
+ baselines.setdefault(value, []).append(cursor_y)
+ return baselines
+
def _assert_checker_and_exporter_reject(
self,
content: str,
@@ -3113,6 +3147,56 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):
text = next(root.iter('{http://www.w3.org/2000/svg}text'))
self.assertEqual(''.join(text.itertext()), '甲 乙')
+ def test_txbody_preview_leading_break_advances_once_at_its_size(self):
+ cases = {'1800': 69.2, '3600': 98.0}
+ for break_size, expected_baseline in cases.items():
+ with self.subTest(break_size=break_size):
+ svg = self._txbody_preview(f'''
+ <a:p>
+ <a:pPr><a:defRPr sz="1800"/></a:pPr>
+ <a:br><a:rPr sz="{break_size}"/></a:br>
+ <a:r><a:rPr sz="1800"/><a:t>B</a:t></a:r>
+ </a:p>''')
+ baselines = self._visible_text_baselines(svg)
+ self.assertAlmostEqual(baselines['B'][0], expected_baseline)
+
+ def test_txbody_preview_empty_break_line_uses_its_own_break_size(self):
+ cases = {
+ ('1800', '1800'): 98.0,
+ ('3600', '1800'): 98.0,
+ ('1800', '3600'): 126.8,
+ }
+ for (first_break, empty_break), expected_baseline in cases.items():
+ with self.subTest(
+ first_break=first_break,
+ empty_break=empty_break,
+ ):
+ svg = self._txbody_preview(f'''
+ <a:p>
+ <a:r><a:rPr sz="1800"/><a:t>A</a:t></a:r>
+ <a:br><a:rPr sz="{first_break}"/></a:br>
+ <a:br><a:rPr sz="{empty_break}"/></a:br>
+ <a:r><a:rPr sz="1800"/><a:t>B</a:t></a:r>
+ </a:p>''')
+ baselines = self._visible_text_baselines(svg)
+ self.assertAlmostEqual(baselines['A'][0], 40.4)
+ self.assertAlmostEqual(baselines['B'][0], expected_baseline)
+
+ def test_txbody_preview_empty_paragraph_uses_end_para_size(self):
+ cases = {'1800': 98.0, '3600': 126.8}
+ for empty_size, expected_baseline in cases.items():
+ with self.subTest(empty_size=empty_size):
+ svg = self._txbody_preview(f'''
+ <a:p><a:r><a:rPr sz="1800"/><a:t>A</a:t></a:r></a:p>
+ <a:p>
+ <a:pPr><a:defRPr sz="1800"/></a:pPr>
+ <a:endParaRPr sz="{empty_size}"/>
+ </a:p>
+ <a:p><a:r><a:rPr sz="1800"/><a:t>B</a:t></a:r></a:p>''')
+ baselines = self._visible_text_baselines(svg)
+ self.assertAlmostEqual(baselines['A'][0], 40.4)
+ self.assertAlmostEqual(baselines['B'][0], expected_baseline)
+
def test_text_property_compatibility_aliases_warn_and_normalize(self):
compatible = '''<svg xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 640 360">