Search code examples
pythonpdfdownloadstreamlit

Streamlit pdf file cannot be opened after downloading with st.download_button


I want to download a pdf on button click in my streamlit application. I am using st.download_button, like this:

st.download_button(
            label="Download",
            key="download_button",
            on_click=None,  # You can specify a callback function if needed
            file_name="MyDocument.pdf",
            data="MyDocumentSource.pdf",
            help="Click to download.",
        )

The pdf file is in the same directory as the python script. And I can open the pdf file as such. However after downloading (which also works), I can not open the pdf file and I get - "file could not be opened due to unsupported datatype".

What am I doing wrong?


Solution

  • The solution is to first read in the pdf as such:

    with open("MyDocumentSource.pdf", "rb") as pdf_file:
        document = pdf_file.read()
    

    Then the data argument needs to be specified as the read in data. Here document and not the path.

    data=document,