Generating PDFs
Never hand-write .pdf with write_file — build it with a real library.
From scratch (structured document) — use reportlab:
pip install reportlab
from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.styles import getSampleStyleSheet
styles = getSampleStyleSheet()
doc = SimpleDocTemplate("/home/user/report.pdf", pagesize=letter)
story = [Paragraph("Title", styles["Title"]), Spacer(1, 12), Paragraph("Body text.", styles["Normal"])]
doc.build(story)
From HTML/CSS (richer layout) — use weasyprint:
pip install weasyprint
from weasyprint import HTML
HTML(string="<h1>Title</h1><p>Body.</p>").write_pdf("/home/user/report.pdf")
weasyprint gives real CSS layout (columns, fonts, page breaks via page-break-after), which is easier for anything visually complex than assembling reportlab flowables by hand — prefer it for anything more than a simple text report.
Present the .pdf with present_file, never the generating script.