"""Apply reader typography to OOXML without round-tripping document content.""" from __future__ import annotations import re import zipfile from pathlib import Path from lxml import etree as ET from .document_style import font_points, length_points, line_points, number, resolved_rules W = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}" NS = {"w": W[1:-1]} def child(parent, name): element = parent.find(W + name) if element is None: element = ET.SubElement(parent, W + name) return element def val(parent, name, value): child(parent, name).set(W + "val", str(value)) def properties(parent, name): element = parent.find(W + name) if element is None: element = ET.Element(W + name) parent.insert(0, element) return element def _order_properties(root): # ECMA-376 property children are ordered. Keep unrelated properties (math, # numbering, bookmarks, tracked changes) while inserting ours in that order. orders = { "pPr": "pStyle keepNext keepLines pageBreakBefore framePr widowControl numPr suppressLineNumbers pBdr shd tabs suppressAutoHyphens kinsoku wordWrap overflowPunct topLinePunct autoSpaceDE autoSpaceDN bidi adjustRightInd snapToGrid spacing ind contextualSpacing mirrorIndents suppressOverlap jc textDirection textAlignment textboxTightWrap outlineLvl divId cnfStyle rPr sectPr pPrChange", "rPr": "rStyle rFonts b bCs i iCs caps smallCaps strike dstrike outline shadow emboss imprint noProof snapToGrid vanish webHidden color spacing w kern position sz szCs highlight u effect bdr shd fitText vertAlign rtl cs em lang eastAsianLayout specVanish oMath rPrChange", } for name, order in orders.items(): ranks = {W + tag: index for index, tag in enumerate(order.split())} for element in root.iter(W + name): element[:] = sorted(element, key=lambda e: ranks.get(e.tag, len(ranks))) def _run_properties(rpr, rule, preserve_emphasis=False): fonts = child(rpr, "rFonts") # Explicit font selections must override the engine's theme fonts. for attr in list(fonts.attrib): if attr.endswith("Theme"): del fonts.attrib[attr] for key in ("ascii", "hAnsi", "cs"): fonts.set(W + key, str(rule["english_font_family"])) fonts.set(W + "eastAsia", str(rule["chinese_font_family"])) size = max(1, round(font_points(rule) * 2)) val(rpr, "sz", size) val(rpr, "szCs", size) for key, xml in (("bold", "b"), ("italic", "i")): existing = rpr.find(W + xml) inline_on = existing is not None and existing.get(W + "val", "1") not in ("0", "false", "off") val(rpr, xml, int(rule[key] or (preserve_emphasis and inline_on))) val(rpr, xml + "Cs", int(rule[key] or (preserve_emphasis and inline_on))) color = child(rpr, "color") color.attrib.clear() color.set(W + "val", str(rule["font_color"]).lstrip("#")) val(rpr, "spacing", round(number(rule["letter_spacing"]) * 20)) def _paragraph_properties(ppr, rule): points = font_points(rule) val(ppr, "jc", "both" if rule["alignment"] == "justify" else rule["alignment"]) spacing = child(ppr, "spacing") spacing.attrib.clear() for side in ("before", "after"): unit = rule[f"space_{side}_unit"] amount = number(rule[f"space_{side}_value"]) spacing.set(W + side, str(round(length_points(amount, unit, points, line_points(rule, points)) * 20))) if unit == "line": spacing.set(W + side + "Lines", str(round(amount * 100))) mode = rule["line_spacing_mode"] spacing.set(W + "line", str(round(number(rule["line_height_value"]) * (240 if mode == "multiple" else 20)))) spacing.set(W + "lineRule", {"multiple": "auto", "exact": "exact", "at_least": "atLeast"}[mode]) ind = child(ppr, "ind") ind.attrib.clear() for side in ("left", "right"): unit, amount = rule[f"{side}_indent_unit"], number(rule[f"{side}_indent_value"]) ind.set(W + side, str(round(length_points(amount, unit, points) * 20))) if unit == "em": ind.set(W + side + "Chars", str(round(amount * 100))) kind = "hanging" if rule["indent_mode"] == "hanging" else "firstLine" amount = number(rule["indent_value"]) if rule["indent_mode"] != "none" else 0 ind.set(W + kind, str(round(amount * points * 20))) ind.set(W + kind + "Chars", str(round(amount * 100))) # Override paragraph style inheritance, including Word's default grid snapping. val(ppr, "snapToGrid", 0) for key, xml in (("contextual_spacing", "contextualSpacing"), ("keep_with_next", "keepNext"), ("keep_lines_together", "keepLines"), ("page_break_before", "pageBreakBefore"), ("widow_control", "widowControl")): val(ppr, xml, int(rule[key])) def apply_docx_styles(path: Path, rules: dict | None = None, *, font_family: str = "", font_size_px: float = 16, preset: str = "default") -> None: effective = resolved_rules(rules, font_family, font_size_px, preset) with zipfile.ZipFile(path) as package: entries = [(info, package.read(info.filename)) for info in package.infolist()] payloads = {info.filename: data for info, data in entries} parser = ET.XMLParser(resolve_entities=False, no_network=True) document = ET.fromstring(payloads["word/document.xml"], parser) styles = ET.fromstring(payloads["word/styles.xml"], parser) style_map = {s.get(W + "styleId"): s for s in styles.findall(W + "style")} def style_chain(style_id): visited = set() while style_id in style_map and style_id not in visited: visited.add(style_id) style = style_map[style_id] yield style base = style.find(W + "basedOn") style_id = base.get(W + "val") if base is not None else None def target_for(paragraph, style_id): chain = list(style_chain(style_id)) names = " ".join([style_id or ""] + [s.find(W + "name").get(W + "val", "") for s in chain if s.find(W + "name") is not None]).lower() heading = re.search(r"heading\s*([1-6])", names) if heading: return "h" + heading[1] if any(word in names for word in ("sourcecode", "source code", "code", "verbatim")): return "code" if any(a.tag == W + "tc" for a in paragraph.iterancestors()): return "table" if "list" in names or paragraph.find("w:pPr/w:numPr", NS) is not None or any(s.find("w:pPr/w:numPr", NS) is not None for s in chain): return "list" if any(word in names for word in ("quote", "quotation", "blockquote", "blocktext", "block text")): return "blockquote" return "paragraph" generated = {} for paragraph in document.iter(W + "p"): ppr = properties(paragraph, "pPr") style_ref = ppr.find(W + "pStyle") original_id = style_ref.get(W + "val", "Normal") if style_ref is not None else "Normal" target = target_for(paragraph, original_id) rule = effective[target] # Preserve the source style chain (numbering, outline levels, table style). # Share one style for all normal body variants so contextual spacing works. key = (target, original_id if target != "paragraph" else "Normal") if key not in generated: identifier = f"MDHelper{len(generated) + 1}" while identifier in style_map: identifier += "x" generated[key] = identifier style = ET.SubElement(styles, W + "style", {W + "type": "paragraph", W + "styleId": identifier}) val(style, "name", f"MDHelper {target} ({key[1]})") if key[1] in style_map: val(style, "basedOn", key[1]) _paragraph_properties(child(style, "pPr"), rule) _run_properties(child(style, "rPr"), rule) val(ppr, "pStyle", generated[key]) paragraph_rule = rule level = ppr.find("w:numPr/w:ilvl", NS) if target == "list" and level is not None and number(level.get(W + "val")) > 0: # Retain nested list levels while applying the selected base indent. paragraph_rule = dict(rule) offset = number(level.get(W + "val")) * 36 if rule["left_indent_unit"] == "em": # A style's leftChars takes precedence over a direct left value; # keep the coordinate system to override that inherited value. paragraph_rule["left_indent_value"] = number(rule["left_indent_value"]) + offset / font_points(rule) else: paragraph_rule["left_indent_value"] = length_points(rule["left_indent_value"], rule["left_indent_unit"], font_points(rule)) + offset paragraph_rule["left_indent_unit"] = "pt" _paragraph_properties(ppr, paragraph_rule) for run in paragraph.iter(W + "r"): rpr = properties(run, "rPr") run_style = rpr.find(W + "rStyle") run_id = run_style.get(W + "val", "") if run_style is not None else "" # Character-level code uses the code font settings; ordinary emphasis # and hyperlinks retain their semantic tags and relationships. run_rule = dict(rule) if "code" in run_id.lower() or "verbatim" in run_id.lower(): for field in ("chinese_font_family", "english_font_family", "font_size", "font_size_unit"): run_rule[field] = effective["code"][field] _run_properties(rpr, run_rule, preserve_emphasis=True) for filename, root in (("word/document.xml", document), ("word/styles.xml", styles)): _order_properties(root) payloads[filename] = ET.tostring(root, encoding="UTF-8", xml_declaration=True, standalone=True) with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED) as package: for info, _ in entries: package.writestr(info, payloads[info.filename])