File size: 1,774 Bytes
a1bf219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)