Streamlit is such an awesome framework that allows you to build several cool data science apps. In this tutorial we will see how to embed PDF files in our streamlit app.
To be able to do so we will need just 2 main things
- st.markdown() : this will enable us to use the same format of embedding files in html in our app.
- base64 encoding: to be able to send our pdf file over we will need to encode it using base64 encoding after opening the file. Without this you will not be able to see the pdf displayed – you will only get a 404 error or something else.
If you are interested in learning more you can check out this material
Let us see how to implement this, below is the entire code and the end result.
Open the File and Encode it
First you will have to open and read the pdf file respectively and then encode it
with open(pdf_file,"rb") as f: base64_pdf = base64.b64encode(f.read()).decode('utf-8')
Parse To HTML Embed Tag
Next you can now parse the base64 encoded file as our src in the embed tag in html
pdf_display = F'<embed src=”data:application/pdf;base64,{base64_pdf}” width=”700″ height=”1000″ type=”application/pdf”>’
Render with Streamlit Markdown
Finally we can use st.markdown to render our result in streamlit.Don’t forget to set as true ‘unsafe_allow_html‘.
st.markdown(pdf_display, unsafe_allow_html=True)
Below is a simple function you can use for this
Thanks for your time
Jesus Saves
By. Jesse E.Agbe(JCharis)