Building PDFs in a streamlit app with fpdf2

fpdf2 is a fast & simple Python library allowing to build PDF documents.

Its documentation include a section about using it inside a streamlit app to generate PDFs: Usage in web APIs - fpdf2.

There is some minimal code to get started:

from base64 import b64encode
from fpdf import FPDF
import streamlit as st

st.title("Demo of fpdf2 usage with streamlit")

@st.cache
def gen_pdf():
    pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Helvetica", size=24)
    pdf.cell(txt="hello world")
    return bytes(pdf.output())

# Embed PDF to display it:
base64_pdf = b64encode(gen_pdf()).decode("utf-8")
pdf_display = f'<embed src="data:application/pdf;base64,{base64_pdf}" width="700" height="400" type="application/pdf">'
st.markdown(pdf_display, unsafe_allow_html=True)

# Add a download button:
st.download_button(
    label="Download PDF",
    data=gen_pdf(),
    file_name="file_name.pdf",
    mime="application/pdf",
)
6 Likes

Nice, would it be possible to make it work across several browsers? the example works fine in Chrome but not Safair. I guess it only works in browsers with some basic form of pdf plugin

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.