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>
132 lines
4.7 KiB
Python
132 lines
4.7 KiB
Python
"""Tests del cálculo y crop de la imagen para modo visual."""
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
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
|
|
AREA_H_EMU = 18_940_000 * 36 // 10 # ≈ 6_818_400
|
|
# Recalculo exacto:
|
|
EMU_POR_CM = 360000
|
|
AREA_W_EMU = int(17.59 * EMU_POR_CM) # 6_332_400
|
|
AREA_H_EMU = int(18.94 * EMU_POR_CM) # 6_818_400
|
|
AREA_ASPECT = AREA_W_EMU / AREA_H_EMU # ≈ 0.929
|
|
|
|
|
|
def _png(tmp_path: Path, w: int, h: int, color: str = "red") -> Path:
|
|
"""Genera un PNG sólido del tamaño dado."""
|
|
from PIL import Image
|
|
p = tmp_path / f"{w}x{h}.png"
|
|
im = Image.new("RGB", (w, h), color)
|
|
im.save(str(p), "PNG")
|
|
return p
|
|
|
|
|
|
def test_portrait_no_recorta_y_llena_alto(tmp_path: Path):
|
|
"""PNG portrait (1275x1650, aspect 0.77) cabe → alto al máximo,
|
|
ancho proporcional menor que el área."""
|
|
p = _png(tmp_path, 1275, 1650)
|
|
w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU)
|
|
|
|
# Alto: lleno
|
|
assert h_emu == AREA_H_EMU
|
|
# Ancho: proporcional, menor que el área
|
|
assert w_emu < AREA_W_EMU
|
|
esperado_w = (AREA_H_EMU * 1275) // 1650
|
|
assert w_emu == esperado_w
|
|
# PNG no debe haberse modificado en píxeles
|
|
from PIL import Image
|
|
with Image.open(str(p)) as im:
|
|
assert im.size == (1275, 1650)
|
|
|
|
|
|
def test_cuadrado_recorta_y_llena_ambos(tmp_path: Path):
|
|
"""PNG 1:1 es más ancho (en proporción) que el área 0.93 → recorta."""
|
|
p = _png(tmp_path, 1500, 1500)
|
|
w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU)
|
|
|
|
# Después del recorte calza el área entera
|
|
assert h_emu == AREA_H_EMU
|
|
assert w_emu == AREA_W_EMU
|
|
# PNG en disco fue recortado a la proporción del área
|
|
from PIL import Image
|
|
with Image.open(str(p)) as im:
|
|
new_iw, new_ih = im.size
|
|
assert new_ih == 1500 # alto intacto
|
|
esperado_iw = int(1500 * AREA_ASPECT)
|
|
assert new_iw == esperado_iw
|
|
assert new_iw < 1500
|
|
|
|
|
|
def test_landscape_recorta_fuerte(tmp_path: Path):
|
|
"""PNG 16:9 (aspect 1.78) muy ancho → recorta agresivo."""
|
|
p = _png(tmp_path, 1600, 900)
|
|
w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU)
|
|
assert h_emu == AREA_H_EMU
|
|
assert w_emu == AREA_W_EMU
|
|
from PIL import Image
|
|
with Image.open(str(p)) as im:
|
|
new_iw, _ = im.size
|
|
esperado = int(900 * AREA_ASPECT) # ~836
|
|
assert new_iw == esperado
|
|
assert new_iw < 1600
|
|
|
|
|
|
def test_idempotente_segunda_llamada_no_recorta(tmp_path: Path):
|
|
"""Una imagen ya recortada no debe mutarse en sitio una segunda vez."""
|
|
p = _png(tmp_path, 1500, 1500)
|
|
_preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU)
|
|
from PIL import Image
|
|
with Image.open(str(p)) as im:
|
|
size_post_1 = im.size
|
|
|
|
w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU)
|
|
# El alto sigue lleno; el ancho puede quedar 1-2 EMU por debajo de
|
|
# AREA_W_EMU por floor() en el crop original. Lo importante: el
|
|
# archivo no se vuelve a tocar.
|
|
assert h_emu == AREA_H_EMU
|
|
assert abs(w_emu - AREA_W_EMU) < AREA_W_EMU // 100 # < 1%
|
|
with Image.open(str(p)) as im:
|
|
size_post_2 = im.size
|
|
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
|
|
ih = 1000
|
|
iw = int(ih * AREA_ASPECT)
|
|
p = _png(tmp_path, iw, ih)
|
|
w_emu, h_emu = _preparar_imagen_visual(p, AREA_W_EMU, AREA_H_EMU)
|
|
assert h_emu == AREA_H_EMU
|
|
# w_emu puede ser ≤ AREA_W_EMU según camino tomado
|
|
from PIL import Image
|
|
with Image.open(str(p)) as im:
|
|
assert im.size == (iw, ih)
|