feat(renderer): márgenes verticales dinámicos para modo visual

En modo visual el área de contenido ahora se calcula a partir de la
geometría REAL del header/footer de la plantilla en lugar de los
márgenes nominales de texto (5/4 cm carta, 6.5/5 cm oficio). El
modo texto sigue usando los nominales — esto solo afecta a visual.

Fórmula:
  top_margin = header_distance + header_height + 0.5 cm (buffer)
  bot_margin = footer_distance + footer_height + 0.5 cm (buffer)

Para las plantillas Collina actuales:
  carta:  top=2.96 cm, bot=1.82 cm  → content_h = 23.16 cm
                                       (antes 18.94 cm, +4.22 cm)
  oficio: top=2.96 cm, bot=1.82 cm  → content_h = 28.24 cm
                                       (antes 21.52 cm, +6.72 cm)

Implementación:
  - Nuevo _medir_header_footer(plantilla_path) lee directamente del
    XML del sectPr (tolera valores fraccionales de twips que
    python-docx rechaza) y mide el cy del drawing más grande de
    header/footer como aproximación de su altura.
  - _renderizar_visual usa esos valores para configurar
    section.top_margin / bottom_margin antes de calcular el área de
    contenido en EMU.
  - renderizar_impresion_visual ahora también mide desde la plantilla
    (sin renderizarla) para que las imágenes caigan en la misma
    posición que el digital al imprimir sobre papel ya membretado.
  - Fallback a márgenes nominales si la medición falla.

Además: tools/diagnostico_plantilla.py para inspeccionar márgenes y
geometría de cualquier plantilla. Útil cuando entreguen plantillas
nuevas o haya que diagnosticar problemas de layout.

Tests: 126 passed. +2 sobre _medir_header_footer con las plantillas
reales del repo (carta y oficio).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
collina-adminandClaude Opus 4.7 committed 2026-05-18 15:40:34 -06:00
1 parent 018beb0059
commit b5288a52bd
3 files changed
+328 -16

No files matched your search

+121 -15
View File
@@ -152,13 +152,18 @@ def renderizar_impresion_visual(
destino: str | Path,
) -> Path:
"""
Modo visual para imprimir: igual que digital_visual pero sin
membrete (para papel ya membretado físicamente).
Modo visual para imprimir: imagen sin membrete, pero usando los
mismos márgenes dinámicos que el digital para que al imprimir sobre
papel ya membretado físicamente las posiciones coincidan.
"""
# Pasamos la plantilla para medir (no se renderiza), así el área
# de contenido coincide con la del digital.
plantilla = _ruta_plantilla(tamano)
plantilla_para_medir = plantilla if plantilla.exists() else None
return _renderizar_visual(
paginas_png=[Path(p) for p in paginas_png],
tamano=tamano,
plantilla_path=None,
plantilla_path=plantilla_para_medir,
destino=Path(destino),
sin_membrete=True,
)
@@ -236,18 +241,26 @@ def _renderizar_visual(
"""
Renderizado visual: cada PNG ocupa una página del DOCX final.
Estrategia:
1. Abre la plantilla (o doc vacío para impresión)
2. Limpia los párrafos vacíos del body
3. Aplica márgenes y tamaño según `tamano`
4. Por cada PNG: salto de página (excepto el primero) + imagen
ajustada al área de contenido (manteniendo aspect ratio)
Márgenes verticales DINÁMICOS:
Para visual queremos que la imagen llene tanto como sea posible
sin pisar el membrete físico. Medimos la altura real del header y
footer de la plantilla y dejamos:
top = header_distance + header_height + buffer
bottom = footer_distance + footer_height + buffer
(buffer = 0.5 cm de respiración).
Esto da un área de contenido más generosa que los márgenes
nominales de texto (5/4 cm para carta), sin tocar el diseño del
membrete. Para impresión usamos los mismos márgenes para que la
imagen caiga en la misma posición al imprimir sobre papel ya
membretado.
Márgenes horizontales: se mantienen los del config (2 cm).
"""
from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.shared import Cm, Emu, Pt
if plantilla_path is not None:
if plantilla_path is not None and not sin_membrete:
doc = Document(str(plantilla_path))
# Limpieza agresiva: en visual mode nuestra imagen ocupa toda el
# área de contenido, así que cualquier drawing del body empuja
@@ -261,14 +274,46 @@ def _renderizar_visual(
agresivo=True,
)
else:
# Impresión sin membrete: doc vacío (la imagen vivirá sola para
# imprimirse sobre papel ya membretado).
doc = Document()
config = CONFIG_POR_TAMANO[tamano]
# ── Márgenes verticales dinámicos ───────────────────────────────────
BUFFER_VISUAL_CM = 0.5
if plantilla_path is not None:
try:
hdr_dist, ftr_dist, hdr_h, ftr_h = _medir_header_footer(
plantilla_path
)
top_margin_cm = hdr_dist + hdr_h + BUFFER_VISUAL_CM
bot_margin_cm = ftr_dist + ftr_h + BUFFER_VISUAL_CM
log.info(
"renderer.visual.margenes_dinamicos",
plantilla=str(plantilla_path),
top_cm=round(top_margin_cm, 2),
bot_cm=round(bot_margin_cm, 2),
header_h_cm=round(hdr_h, 2),
footer_h_cm=round(ftr_h, 2),
)
except Exception as e:
log.warning(
"renderer.visual.medicion_fallida",
plantilla=str(plantilla_path),
error=str(e),
)
top_margin_cm = config.margen_superior_cm
bot_margin_cm = config.margen_inferior_cm
else:
top_margin_cm = config.margen_superior_cm
bot_margin_cm = config.margen_inferior_cm
for section in doc.sections:
section.page_width = Cm(config.ancho_cm)
section.page_height = Cm(config.alto_cm)
section.top_margin = Cm(config.margen_superior_cm)
section.bottom_margin = Cm(config.margen_inferior_cm)
section.top_margin = Cm(top_margin_cm)
section.bottom_margin = Cm(bot_margin_cm)
section.left_margin = Cm(config.margen_izquierdo_cm)
section.right_margin = Cm(config.margen_derecho_cm)
@@ -282,9 +327,7 @@ def _renderizar_visual(
- config.margen_derecho_cm) * EMU_POR_CM
)
content_h_emu = int(
(config.alto_cm
- config.margen_superior_cm
- config.margen_inferior_cm) * EMU_POR_CM
(config.alto_cm - top_margin_cm - bot_margin_cm) * EMU_POR_CM
)
for i, png in enumerate(paginas_png):
@@ -328,6 +371,69 @@ def _renderizar_visual(
return destino
_W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
def _twips_a_cm(s: str | None) -> float | None:
if s is None:
return None
try:
return float(s) * 2.54 / 1440
except (TypeError, ValueError):
return None
def _medir_header_footer(
plantilla_path: Path,
) -> tuple[float, float, float, float]:
"""
Mide la geometría real del header y footer de la plantilla.
Lee directamente del XML del sectPr (no usa `Section.*_distance.cm`)
porque algunas plantillas autoreadas vienen con valores en twips
fraccionales que python-docx rechaza al parsear.
Devuelve (header_distance_cm, footer_distance_cm,
header_height_cm, footer_height_cm).
La altura se estima como el max(cy de drawings, 0.5 cm) — las
membretadas Collina tienen el contenido principal en una imagen, así
que el cy del drawing es una buena aproximación. 0.5 cm es el
fallback cuando solo hay texto, equivalente a una línea pequeña.
"""
from docx import Document
import re as _re
doc = Document(str(plantilla_path))
section = doc.sections[0]
sectpr = section._sectPr # type: ignore[attr-defined]
pg_mar = sectpr.find(f".//{{{_W_NS}}}pgMar")
hdr_dist = (
_twips_a_cm(pg_mar.get(f"{{{_W_NS}}}header"))
if pg_mar is not None
else None
) or 0.0
ftr_dist = (
_twips_a_cm(pg_mar.get(f"{{{_W_NS}}}footer"))
if pg_mar is not None
else None
) or 0.0
EMU_POR_CM = 360000
def _max_drawing_cy_cm(elem) -> float:
xml = elem.xml
extents = _re.findall(r'<wp:extent cx="(\d+)" cy="(\d+)"', xml)
alturas = [int(cy) / EMU_POR_CM for _, cy in extents]
return max(alturas) if alturas else 0.5
hdr_height = _max_drawing_cy_cm(section.header._element)
ftr_height = _max_drawing_cy_cm(section.footer._element)
return hdr_dist, ftr_dist, hdr_height, ftr_height
def _preparar_imagen_visual(
png_path: Path,
area_w_emu: int,
+25 -1
View File
@@ -3,7 +3,7 @@ from pathlib import Path
import pytest
from valeria.renderer import _preparar_imagen_visual
from valeria.renderer import _medir_header_footer, _preparar_imagen_visual
# Área de contenido carta: 17.59 x 18.94 cm
AREA_W_EMU = 17_590_000 * 36 // 10 # ≈ 6_332_400
@@ -93,6 +93,30 @@ def test_idempotente_segunda_llamada_no_recorta(tmp_path: Path):
assert size_post_2 == size_post_1
# ── _medir_header_footer (sobre las plantillas reales) ────────────────────
def test_medir_carta_real():
plantilla = Path("plantillas/carta.docx")
if not plantilla.exists():
pytest.skip("plantilla real no disponible")
hdr_dist, ftr_dist, hdr_h, ftr_h = _medir_header_footer(plantilla)
# Valores conocidos por el script de diagnóstico
assert abs(hdr_dist - 0.50) < 0.05
assert abs(ftr_dist - 0.50) < 0.05
assert 1.5 < hdr_h < 2.5 # ~1.96 cm
assert 0.3 < ftr_h < 1.5 # ~0.82 cm
def test_medir_oficio_real():
plantilla = Path("plantillas/oficio.docx")
if not plantilla.exists():
pytest.skip("plantilla real no disponible")
hdr_dist, ftr_dist, hdr_h, ftr_h = _medir_header_footer(plantilla)
assert abs(hdr_dist - 0.50) < 0.05
assert abs(ftr_dist - 0.50) < 0.05
assert 1.5 < hdr_h < 2.5
assert 0.3 < ftr_h < 1.5
def test_exactamente_aspect_del_area_no_recorta(tmp_path: Path):
"""Si el PNG ya tiene exactamente el aspect del área, no se toca."""
# Construyo un PNG con exactamente el aspect del área
+182
View File
@@ -0,0 +1,182 @@
"""
Diagnóstico de una plantilla membretada Collina.
Reporta dimensiones de página, márgenes, distancias y la altura
medida del contenido de header y footer (sumando imágenes inline y
estimando texto). Útil para calcular el área de contenido real
disponible para el modo visual.
Uso:
PYTHONPATH=src python tools/diagnostico_plantilla.py [ruta.docx]
Por defecto inspecciona plantillas/carta.docx.
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
from docx import Document
from docx.oxml.ns import qn
EMU_POR_CM = 360000
W_NS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
def _emu_a_cm(emu: int | None) -> float:
return (emu or 0) / EMU_POR_CM
def _twips_a_cm(twips_str: str | None) -> float | None:
"""Convierte un valor en twips (1/1440 de pulgada) a cm. Tolera
valores fraccionales que python-docx rechaza."""
if twips_str is None:
return None
try:
return float(twips_str) * 2.54 / 1440
except (TypeError, ValueError):
return None
def _atributo_pgmar(sectpr, sufijo: str) -> str | None:
pg_mar = sectpr.find(f".//{{{W_NS}}}pgMar")
if pg_mar is None:
return None
return pg_mar.get(f"{{{W_NS}}}{sufijo}")
def _atributo_pgsz(sectpr, sufijo: str) -> str | None:
pg_sz = sectpr.find(f".//{{{W_NS}}}pgSz")
if pg_sz is None:
return None
return pg_sz.get(f"{{{W_NS}}}{sufijo}")
def _altura_drawings_en(elemento) -> tuple[float, list[float]]:
"""Suma cy de todos los <wp:extent> en el subárbol. Devuelve
(suma_cm, lista_individual_cm)."""
xml = elemento.xml
extents = re.findall(r'<wp:extent cx="(\d+)" cy="(\d+)"', xml)
alturas_cm = [int(cy) / EMU_POR_CM for _, cy in extents]
return sum(alturas_cm), alturas_cm
def _estimar_altura_texto(parrafos) -> tuple[float, int]:
"""Estimación gruesa: cada párrafo con texto cuenta como una línea
de 12 pt (~0.42 cm) más spacing por defecto. Si tiene un drawing,
el alto del drawing domina y no añadimos línea.
"""
PT_A_CM = 2.54 / 72
altura_cm = 0.0
lineas = 0
for p in parrafos:
tiene_drawing = bool(p._element.findall(f".//{qn('w:drawing')}"))
if tiene_drawing:
continue
# Buscar tamaño de fuente declarado en runs, default 11 pt
size_pt = 11
for run in p.runs:
sz = run.font.size
if sz is not None:
size_pt = sz.pt
break
if not p.text.strip():
# Párrafo vacío: cuenta como interlineado mínimo (1 line)
altura_cm += size_pt * PT_A_CM
else:
altura_cm += size_pt * PT_A_CM * 1.15 # interlineado típico
lineas += 1
return altura_cm, lineas
def diagnosticar(path: Path) -> None:
print(f"=== {path} ===\n")
if not path.exists():
print(f"NO EXISTE: {path}")
return
doc = Document(str(path))
s = doc.sections[0]
sectpr = s._sectPr # type: ignore[attr-defined]
# Leemos los márgenes directo del XML para tolerar valores fraccionales
# que python-docx rechaza al parsear (algunas plantillas autoreadas
# por LibreOffice/Pages traen floats en lugar de int twips).
page_h_cm = _twips_a_cm(_atributo_pgsz(sectpr, "h")) or 0.0
page_w_cm = _twips_a_cm(_atributo_pgsz(sectpr, "w")) or 0.0
top_cm = _twips_a_cm(_atributo_pgmar(sectpr, "top")) or 0.0
bot_cm = _twips_a_cm(_atributo_pgmar(sectpr, "bottom")) or 0.0
left_cm = _twips_a_cm(_atributo_pgmar(sectpr, "left")) or 0.0
right_cm = _twips_a_cm(_atributo_pgmar(sectpr, "right")) or 0.0
hdr_dist_cm = _twips_a_cm(_atributo_pgmar(sectpr, "header")) or 0.0
ftr_dist_cm = _twips_a_cm(_atributo_pgmar(sectpr, "footer")) or 0.0
print("PÁGINA Y MÁRGENES (leídos del XML del sectPr)")
print(f" page_height = {page_h_cm:.2f} cm")
print(f" page_width = {page_w_cm:.2f} cm")
print(f" top_margin = {top_cm:.2f} cm")
print(f" bottom_margin = {bot_cm:.2f} cm")
print(f" left_margin = {left_cm:.2f} cm")
print(f" right_margin = {right_cm:.2f} cm")
print(f" header_distance = {hdr_dist_cm:.2f} cm "
f"(borde superior → inicio del header)")
print(f" footer_distance = {ftr_dist_cm:.2f} cm "
f"(borde inferior → inicio del footer)")
print()
print("HEADER (contenido)")
drs_h, alturas_drs_h = _altura_drawings_en(s.header._element)
txt_h, n_lineas_h = _estimar_altura_texto(s.header.paragraphs)
print(f" drawings: {len(alturas_drs_h)} "
f"alturas={[round(a,2) for a in alturas_drs_h]} cm")
print(f" altura_drawings: {drs_h:.2f} cm")
print(f" texto: {n_lineas_h} línea(s) con contenido, "
f"~{txt_h:.2f} cm")
altura_header = max(drs_h, txt_h) # imagen y texto suelen superponerse
print(f" altura_total_aprox: {altura_header:.2f} cm "
f"(max de drawings y texto)")
print()
print("FOOTER (contenido)")
drs_f, alturas_drs_f = _altura_drawings_en(s.footer._element)
txt_f, n_lineas_f = _estimar_altura_texto(s.footer.paragraphs)
print(f" drawings: {len(alturas_drs_f)} "
f"alturas={[round(a,2) for a in alturas_drs_f]} cm")
print(f" altura_drawings: {drs_f:.2f} cm")
print(f" texto: {n_lineas_f} línea(s) con contenido, "
f"~{txt_f:.2f} cm")
altura_footer = max(drs_f, txt_f)
print(f" altura_total_aprox: {altura_footer:.2f} cm")
print()
print("ÁREA DE CONTENIDO")
nominal_alto = page_h_cm - top_cm - bot_cm
print(f" nominal (page - top - bottom):")
print(f" {nominal_alto:.2f} cm = {page_h_cm:.2f} - {top_cm:.2f} - "
f"{bot_cm:.2f}")
# Cómputo "real" considerando contenido de header y footer.
inicio_header_cm = hdr_dist_cm
fin_header_cm = inicio_header_cm + altura_header
inicio_footer_cm = page_h_cm - ftr_dist_cm - altura_footer
contenido_inicio = max(top_cm, fin_header_cm)
contenido_fin = min(page_h_cm - bot_cm, inicio_footer_cm)
contenido_alto_real = max(0.0, contenido_fin - contenido_inicio)
print(f" real (descontando contenido de header y footer):")
print(f" header termina a {fin_header_cm:.2f} cm del tope")
print(f" footer empieza a {inicio_footer_cm:.2f} cm del tope")
print(f" contenido va de {contenido_inicio:.2f} a {contenido_fin:.2f} "
f"cm → alto disponible = {contenido_alto_real:.2f} cm")
if contenido_alto_real < nominal_alto:
print(
f" ⚠ Header/footer reales son más grandes que los márgenes "
f"nominales. La imagen del modo visual debe usar "
f"{contenido_alto_real:.2f} cm de alto en vez de "
f"{nominal_alto:.2f}."
)
if __name__ == "__main__":
arg = sys.argv[1] if len(sys.argv) > 1 else "plantillas/carta.docx"
diagnosticar(Path(arg))