Welcome to the Streamlit community!
You’re on the right track with your form, and your question is a common one for folks building data collection apps. Let’s break down the best practice for your workflow:
1. Handle form submission:
Use st.form and st.form_submit_button to batch user input and only process data after the user clicks “Submit”. Place all your input widgets inside the form context. The variable submitted will be True only after the user submits the form—make sure any logic that depends on form data (like generating files) is inside an if submitted: block, and outside the with st.form(…) context. See st.form documentation.
2. Generate the PDF file:
Streamlit doesn’t natively generate PDFs, but you can use libraries like FPDF or ReportLab. After submission, use the form data to create a PDF in memory (not on disk, to avoid file system issues on Streamlit Cloud). Save the PDF to a BytesIO buffer.
3. Display a download button after submission:
After generating the PDF, use st.download_button to let the user download the file. Place this button inside the if submitted: block, outside the form. Don’t put st.download_button inside the form—Streamlit doesn’t allow it (see docs).
Example (using FPDF):
import streamlit as st
from fpdf import FPDF
from io import BytesIO
with st.form("fpe_form"):
firstname = st.text_input("Firstname")
lastname = st.text_input("Lastname")
# ... add other fields ...
submitted = st.form_submit_button("Submit")
if submitted:
# Generate PDF in memory
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, txt=f"Name: {firstname} {lastname}", ln=1)
# ... add more fields ...
pdf_buffer = BytesIO()
pdf.output(pdf_buffer)
pdf_buffer.seek(0)
st.success("Form submitted! Click below to download.")
st.download_button(
label="Download PDF",
data=pdf_buffer,
file_name=f"{lastname}_{firstname}.pdf",
mime="application/pdf"
)
This approach avoids file system issues and ensures the download button only appears after submission. For more details, see this forum example and official docs.
Sources: