""" Shared PDF generation helper for any model using the hospital letterhead. """ import io import base64 from django.conf import settings from django.template.loader import render_to_string from weasyprint import HTML def _get_logo_data_uri(): """Load the HH_P_ICON as a base64 data URI for embedding in PDF.""" try: from PIL import Image as PILImage logo_img = PILImage.open(settings.BASE_DIR / "static" / "img" / "HH_P_ICON.png") logo_img.thumbnail((600, 600), PILImage.LANCZOS) buf = io.BytesIO() logo_img.save(buf, format="PNG", optimize=True) return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode() except Exception: return None def generate_letterhead_pdf(template_name, context, filename): """Render a template with the hospital letterhead and return an HttpResponse with the PDF.""" from django.http import HttpResponse logo_path = _get_logo_data_uri() full_context = {**context, "logo_path": logo_path} html_string = render_to_string(template_name, full_context) pdf_file = HTML(string=html_string, base_url=str(settings.BASE_DIR / "static")).write_pdf() response = HttpResponse(pdf_file, content_type="application/pdf") response["Content-Disposition"] = f'attachment; filename="{filename}"' return response