Spaces:
Sleeping
Sleeping
| """PDF generation utilities for analysis reports.""" | |
| import logging | |
| from typing import Optional | |
| logger = logging.getLogger(__name__) | |
| def generate_pdf_from_html(html_content: str, output_path: Optional[str] = None) -> str: | |
| """Generate PDF from HTML content. | |
| Args: | |
| html_content: HTML content to convert | |
| output_path: Optional output path for PDF file. If None, uses temp file. | |
| Returns: | |
| Path to generated PDF file | |
| Raises: | |
| ImportError: If weasyprint is not installed | |
| Exception: If PDF generation fails | |
| """ | |
| try: | |
| from weasyprint import HTML | |
| except ImportError: | |
| logger.error("weasyprint not installed. Install with: pip install weasyprint") | |
| raise ImportError( | |
| "PDF export requires weasyprint. Install with: pip install weasyprint" | |
| ) | |
| try: | |
| # Generate PDF | |
| if output_path is None: | |
| import tempfile | |
| fd, output_path = tempfile.mkstemp(suffix=".pdf") | |
| import os | |
| os.close(fd) | |
| logger.info(f"Generating PDF at {output_path}") | |
| # Convert HTML to PDF | |
| HTML(string=html_content).write_pdf(output_path) | |
| logger.info(f"PDF generated successfully: {output_path}") | |
| return output_path | |
| except Exception as e: | |
| logger.error(f"PDF generation failed: {str(e)}") | |
| raise | |
| def generate_pdf_from_report(report, output_path: Optional[str] = None) -> str: | |
| """Generate PDF from AnalysisReport object. | |
| Args: | |
| report: AnalysisReport object | |
| output_path: Optional output path for PDF file | |
| Returns: | |
| Path to generated PDF file | |
| """ | |
| html_content = report.to_html() | |
| return generate_pdf_from_html(html_content, output_path) | |