Spaces:
Sleeping
Sleeping
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}") | |