"""pdf_from_html — convierte HTML string a PDF usando weasyprint (stub si no disponible)."""
def pdf_from_html(
html_string: str,
output_path: str,
page_size: str = "A4",
css: str = "",
) -> str:
"""Convierte un HTML string a PDF usando weasyprint.
Soporta CSS inline y externo (pasado como string). Produce PDFs de alta
calidad tipografica con soporte completo de CSS layout (columnas, grids,
fuentes web).
NOTA: Requiere weasyprint y sus dependencias de sistema (pango, cairo,
gdk-pixbuf). Instalar con: pip install weasyprint
En Linux: apt install libpango-1.0-0 libcairo2 libgdk-pixbuf-2.0-0
Args:
html_string: contenido HTML completo como string.
output_path: ruta donde guardar el PDF generado.
page_size: tamaño de pagina CSS: 'A4', 'letter', 'A3'. Por defecto 'A4'.
css: CSS adicional como string para aplicar sobre el HTML.
Returns:
output_path con el PDF guardado.
Raises:
RuntimeError: si weasyprint no esta instalado.
"""
try:
import weasyprint
except ImportError as exc:
raise RuntimeError(
"weasyprint no esta instalado. "
"Instalar con: pip install weasyprint\n"
"Dependencias de sistema (Linux): "
"apt install libpango-1.0-0 libcairo2 libgdk-pixbuf-2.0-0"
) from exc
page_css = f"@page {{ size: {page_size}; }}"
full_css = page_css + "\n" + css if css else page_css
html = weasyprint.HTML(string=html_string)
stylesheet = weasyprint.CSS(string=full_css)
html.write_pdf(output_path, stylesheets=[stylesheet])
return output_path