export_pdf.py
2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from __future__ import annotations
import argparse
import json
import sys
from datetime import datetime
from pathlib import Path
from typing import Optional
PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from services.engines.report.renderers.pdf_renderer import PDFRenderer
from utils.runtime_paths import FINAL_REPORTS_DIR, ensure_runtime_dirs
def resolve_input_path(raw_path: Optional[str]) -> Optional[Path]:
if raw_path:
path = Path(raw_path).expanduser()
if not path.is_absolute():
path = PROJECT_ROOT / path
return path
ensure_runtime_dirs()
ir_dir = FINAL_REPORTS_DIR / "ir"
if not ir_dir.exists():
return None
candidates = sorted(ir_dir.glob("*.json"), key=lambda item: item.stat().st_mtime, reverse=True)
return candidates[0] if candidates else None
def export_pdf(ir_file_path: Path) -> Path:
with ir_file_path.open("r", encoding="utf-8") as file:
document_ir = json.load(file)
renderer = PDFRenderer()
pdf_bytes = renderer.render_to_bytes(document_ir, optimize_layout=True)
topic = document_ir.get("metadata", {}).get("topic", "report")
output_dir = FINAL_REPORTS_DIR / "pdf"
output_dir.mkdir(parents=True, exist_ok=True)
filename = f"report_{topic}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
output_path = output_dir / filename
output_path.write_bytes(pdf_bytes)
return output_path
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="Export a report IR JSON file to PDF.")
parser.add_argument(
"input",
nargs="?",
help="Path to a report IR JSON file. Defaults to the newest file under var/reports/final/ir.",
)
return parser
def main(argv: Optional[list[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
input_path = resolve_input_path(args.input)
if input_path is None or not input_path.exists():
parser.error("Could not find a report IR JSON file to export.")
output_path = export_pdf(input_path)
print(output_path)
return 0
if __name__ == "__main__":
raise SystemExit(main())