I am using PyFPDF to create custom PDF documents automatically when a user registers using my custom-built Django application. The PDFs contain information about that persons registration. For each person that registers, I do not want to save their pdf as a separate pdf - I want to mail their PDF immediately after I have formatted it.
pdf = FPDF()
pdf.add_page()
pdf.image(file_path, 0, 0, 210)
pdf.set_text_color(1, 164, 206)
pdf.set_font("helvetica", size=26)
pdf.ln(142)
pdf.cell(0, 0, txt=name, ln=4, align="C")
This is what I have currently to format the PDF, where name
is a value retrieved from each individual user's registration.
This is what comes immediately after, and what I want to replace:
val = uuid.uuid4().hex
pdf.output(val+".pdf")
Right now, I am exporting each PDF with a unique filename, and then sending it to each user's email.
What I would prefer is to use the pdf
variable directly when sending each email, as below:
finalEmail = EmailMessage(
subject,
plain_message,
from_email,
[email]
)
finalEmail.attach("Registration.pdf", pdf)
finalEmail.send()
However, Django does not accept this as a valid attachment type, as it is a FPDF variable still.
expected bytes-like object, not FPDF
How would I go about this?
In documentation you can see parameter S
which gives it as bytes string
content = pdf.output(val+".pdf", 'S')
and now you can use content
to create attachement in email.