Spaces:
Sleeping
Sleeping
| from __future__ import annotations | |
| from datetime import datetime | |
| from typing import Any, Dict | |
| from jinja2 import Environment, FileSystemLoader, select_autoescape | |
| from weasyprint import HTML | |
| from .config import BASE_DIR # si lo usas para rutas | |
| TEMPLATES_DIR = BASE_DIR / "templates" | |
| TEMPLATE_MAP: Dict[str, str] = { | |
| "RESTlet": "RESTlet.html.j2", | |
| "ClientScript": "ClientScript.html.j2", | |
| "Map/Reduce": "MapReduce.html.j2", | |
| "MapReduce": "MapReduce.html.j2", | |
| "Scheduled": "ScheduledScript.html.j2", | |
| "ScheduledScript": "ScheduledScript.html.j2", | |
| "Suitelet": "Suitelet.html.j2", | |
| "UserEvent": "UserEventScript.html.j2", | |
| "UserEventScript": "UserEventScript.html.j2", | |
| "UserModule.js": "InternalModule.html.j2", | |
| "InternalModule": "InternalModule.html.j2", | |
| } | |
| env = Environment( | |
| loader=FileSystemLoader(str(TEMPLATES_DIR)), | |
| autoescape=select_autoescape(["html", "xml"]), | |
| trim_blocks=True, | |
| lstrip_blocks=True, | |
| ) | |
| def _resolve_template(doc: Dict[str, Any]) -> str: | |
| metadata = doc.get("metadata") or {} | |
| script_type = ( | |
| metadata.get("script_type") or metadata.get("type") or "InternalModule" | |
| ) | |
| return TEMPLATE_MAP.get(script_type, "InternalModule.html.j2") | |
| def render_html(doc: Dict[str, Any]) -> str: | |
| template_name = _resolve_template(doc) | |
| template = env.get_template(template_name) | |
| html = template.render( | |
| doc=doc, | |
| generated_at=datetime.utcnow().strftime("%Y-%m-%d %H:%M UTC"), | |
| ) | |
| return html | |
| def render_pdf_bytes(doc: Dict[str, Any]) -> bytes: | |
| """ | |
| Genera un PDF vectorial a partir del HTML usando WeasyPrint. | |
| El texto es seleccionable. | |
| """ | |
| html = render_html(doc) | |
| # base_url permite que WeasyPrint resuelva rutas relativas (si tuvieras CSS/imagenes locales) | |
| pdf_bytes: bytes = HTML(string=html, base_url=str(TEMPLATES_DIR)).write_pdf() | |
| return pdf_bytes | |