121 lines
6.4 KiB
Python
121 lines
6.4 KiB
Python
"""Apply reader typography to OOXML without round-tripping document content."""
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from lxml import etree as ET
|
|
|
|
from .document_style import font_points, length_points, line_points, number
|
|
|
|
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 = {
|
|
'numbering': 'numPicBullet abstractNum num numIdMacAtCleanup',
|
|
'style': 'name aliases basedOn next link autoRedefine hidden uiPriority semiHidden unhideWhenUsed qFormat locked personal personalCompose personalReply rsid pPr rPr tblPr trPr tcPr tblStylePr',
|
|
'tblPr': 'tblStyle tblpPr tblOverlap bidiVisual tblStyleRowBandSize tblStyleColBandSize tblW jc tblCellSpacing tblInd tblBorders shd tblLayout tblCellMar tblLook tblCaption tblDescription tblPrChange',
|
|
'tcPr': 'cnfStyle tcW gridSpan hMerge vMerge tcBorders shd noWrap tcMar textDirection tcFitText vAlign hideMark cellIns cellDel cellMerge tcPrChange',
|
|
"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):
|
|
"""Write only declared fields; character styles must inherit paragraph fonts."""
|
|
fonts = child(rpr, "rFonts") if any(k in rule for k in ('english_font_family', 'chinese_font_family')) else None
|
|
# Explicit font selections must override the engine's theme fonts.
|
|
for attr in list(fonts.attrib) if fonts is not None else []:
|
|
if attr.endswith("Theme"):
|
|
del fonts.attrib[attr]
|
|
if 'english_font_family' in rule:
|
|
for key in ("ascii", "hAnsi", "cs"):
|
|
fonts.set(W + key, str(rule["english_font_family"]))
|
|
if 'chinese_font_family' in rule: fonts.set(W + "eastAsia", str(rule['chinese_font_family']))
|
|
if 'font_size' in rule:
|
|
size = max(1, round(font_points(rule) * 2))
|
|
val(rpr, "sz", size)
|
|
val(rpr, "szCs", size)
|
|
for key, xml in (("bold", "b"), ("italic", "i"), ('strike', 'strike')):
|
|
if key in rule:
|
|
val(rpr, xml, int(rule[key]))
|
|
if key != 'strike': val(rpr, xml + 'Cs', int(rule[key]))
|
|
if 'font_color' in rule:
|
|
color = child(rpr, "color")
|
|
color.attrib.clear()
|
|
color.set(W + "val", str(rule["font_color"]).lstrip("#"))
|
|
if 'letter_spacing' in rule: val(rpr, "spacing", round(number(rule["letter_spacing"]) * 20))
|
|
if 'underline' in rule: val(rpr, 'u', 'single' if rule['underline'] else 'none')
|
|
if 'background_color' in rule:
|
|
shade = child(rpr, 'shd')
|
|
shade.set(W + 'val', 'clear')
|
|
shade.set(W + 'fill', str(rule['background_color']).lstrip('#') if rule['background_color'] != 'transparent' else 'auto')
|
|
|
|
|
|
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)
|
|
if 'background_color' in rule:
|
|
shade = child(ppr, 'shd')
|
|
shade.set(W + 'val', 'clear')
|
|
shade.set(W + 'fill', str(rule['background_color']).lstrip('#') if rule['background_color'] != 'transparent' else 'auto')
|
|
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:
|
|
from .docx_semantic import apply_semantic_styles
|
|
apply_semantic_styles(path, rules, font_family=font_family, font_size_px=font_size_px, preset=preset)
|