File size: 1,149 Bytes
0d18784
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from io import BytesIO
import json

def generate_pdf(report_data: dict) -> BytesIO:
    """
    Generates a PDF file from the given report data.

    Args:
        report_data (dict): The data to include in the PDF.

    Returns:
        BytesIO: A buffer containing the generated PDF.
    """
    try:
        # Create a buffer to store the PDF in memory
        buffer = BytesIO()
        c = canvas.Canvas(buffer, pagesize=letter)

        # Set up the text properties
        text = c.beginText(40, 750)  # Starting position
        text.setFont("Helvetica", 10)

        # Convert the report data dictionary to a formatted JSON string
        report_str = json.dumps(report_data, indent=4)

        # Write each line of the JSON string to the PDF
        for line in report_str.splitlines():
            text.textLine(line)

        c.drawText(text)
        c.showPage()
        c.save()

        # Rewind the buffer to the beginning
        buffer.seek(0)
        return buffer
    except Exception as e:
        raise RuntimeError(f"Failed to generate PDF: {e}")