Display pdf in streamlit

I’m using this simple code to try to display a pdf using from streamlit_pdf_viewer:

from streamlit_pdf_viewer import pdf_viewer


container_pdf, container_chat = st.columns([50, 50])


with container_pdf:
    pdf_file = st.file_uploader("Upload PDF file", type=('pdf'))

    if pdf_file:
        binary_data = pdf_file.getvalue()
        pdf_viewer(input=binary_data,
                   width=700)

But when I upload a pdf I get this error on the browser (not on my IDE):

Component Error

Message: TypeError: Cannot read properties of null (reading 'length')

I thought it was some badly formed PDF so I tried it on the app they provide here: https://structure-vision.streamlit.app/

and strangely enough it loads my PDF with no issues.

So I looked into the code for this app here: GitHub - lfoppiano/structure-vision: Viewer for the structure extracted by Grobid on PDF documents

And I don’t see anything too different on how they read and display the PDF apart from the annotation stuff so what is happening? Can someone try this and tell me if it’s working for them?

The pdf_file might be lost as you navigate to other pages or some reruns. It is better to store it in session state.

from streamlit import session_state as ss

# Declare variable.
if 'pdf_ref' not in ss:
    ss.pdf_ref = None

Upload the file and save the uploaded file reference in the session variable.

# Access the uploaded ref via a key.
st.file_uploader("Upload PDF file", type=('pdf'), key='pdf')

if ss.pdf:
    ss.pdf_ref = ss.pdf  # backup

Use the saved pdf_ref.

# Now you can access "pdf_ref" anywhere in your app.
if ss.pdf_ref:
    binary_data = ss.pdf_ref.getvalue()
    pdf_viewer(input=binary_data, width=700)

Complete sample code.

from streamlit import session_state as ss
from streamlit_pdf_viewer import pdf_viewer


# Declare variable.
if 'pdf_ref' not in ss:
    ss.pdf_ref = None


# Access the uploaded ref via a key.
st.file_uploader("Upload PDF file", type=('pdf'), key='pdf')

if ss.pdf:
    ss.pdf_ref = ss.pdf  # backup

# Now you can access "pdf_ref" anywhere in your app.
if ss.pdf_ref:
    binary_data = ss.pdf_ref.getvalue()
    pdf_viewer(input=binary_data, width=700)

So even if the pdf filename is no longer visible, the pdf is still viewable.

Reference

File Uploader

3 Likes

Thanks for the answer! It was a bug, I reported it and is now fixed in the latest version. Now it is working for me.

3 Likes

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