Spaces:
Sleeping
Sleeping
File size: 3,171 Bytes
c3bc936 | 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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | """
PDF export utilities for email drafts.
"""
from fpdf import FPDF
from typing import Optional
class EmailPDFExporter:
"""Export emails to PDF format."""
def __init__(self):
self.pdf = None
def export_to_pdf(self, subject: str, email_content: str,
sender_name: Optional[str] = None,
recipient_name: Optional[str] = None) -> bytes:
"""Export email to PDF and return as bytes."""
self.pdf = FPDF()
self.pdf.add_page()
self.pdf.set_auto_page_break(auto=True, margin=15)
# Calculate usable width
effective_width = self.pdf.w - 2 * self.pdf.l_margin
# Set up fonts
self.pdf.set_font("Helvetica", "B", 16)
# Title
self.pdf.cell(effective_width, 10, "Email Draft", new_x="LMARGIN", new_y="NEXT", align="C")
self.pdf.ln(5)
# Subject - handle long subjects
self.pdf.set_font("Helvetica", "B", 12)
subject_text = f"Subject: {subject}" if subject else "Subject: (No subject)"
self.pdf.multi_cell(effective_width, 8, subject_text)
self.pdf.ln(2)
# From/To if provided
if sender_name:
self.pdf.set_font("Helvetica", "", 10)
self.pdf.cell(effective_width, 8, f"From: {sender_name}", new_x="LMARGIN", new_y="NEXT")
if recipient_name:
self.pdf.set_font("Helvetica", "", 10)
self.pdf.cell(effective_width, 8, f"To: {recipient_name}", new_x="LMARGIN", new_y="NEXT")
self.pdf.ln(5)
# Horizontal line
self.pdf.set_draw_color(200, 200, 200)
self.pdf.line(self.pdf.l_margin, self.pdf.get_y(), self.pdf.w - self.pdf.r_margin, self.pdf.get_y())
self.pdf.ln(5)
# Email content
self.pdf.set_font("Helvetica", "", 11)
# Handle multi-line content safely
for line in email_content.split('\n'):
if line.strip():
# Encode to handle special characters
safe_line = line.encode('latin-1', errors='replace').decode('latin-1')
self.pdf.multi_cell(effective_width, 6, safe_line)
else:
self.pdf.ln(4)
# Return as bytes (fpdf2 returns bytes directly)
return bytes(self.pdf.output())
def save_to_file(self, filepath: str, subject: str, email_content: str,
sender_name: Optional[str] = None,
recipient_name: Optional[str] = None):
"""Export email to PDF file."""
pdf_bytes = self.export_to_pdf(subject, email_content, sender_name, recipient_name)
with open(filepath, 'wb') as f:
f.write(pdf_bytes)
def export_email_to_pdf(subject: str, email_content: str,
sender_name: Optional[str] = None,
recipient_name: Optional[str] = None) -> bytes:
"""Convenience function to export email to PDF bytes."""
exporter = EmailPDFExporter()
return exporter.export_to_pdf(subject, email_content, sender_name, recipient_name)
|