|
import tempfile |
|
import streamlit as st |
|
import os |
|
|
|
def create_pdf_download_button(pdf_path): |
|
|
|
if not os.path.exists(pdf_path): |
|
st.error(f"The PDF file '{os.path.basename(pdf_path)}' was not found.") |
|
return |
|
|
|
|
|
st.markdown( |
|
f""" |
|
<a href="data:application/pdf;base64,{base64_encode_file(pdf_path)}" |
|
download="{os.path.basename(pdf_path)}" |
|
class="streamlit-button"> |
|
Download PDF |
|
</a> |
|
""", |
|
unsafe_allow_html=True, |
|
) |
|
|
|
def base64_encode_file(file_path): |
|
|
|
with open(file_path, "rb") as file: |
|
encoded_data = base64.b64encode(file.read()).decode() |
|
|
|
return encoded_data |
|
|
|
def main(): |
|
if "tmp_dir" not in st.session_state: |
|
st.session_state.tmp_dir = tempfile.TemporaryDirectory() |
|
if "temp_pdf_path" not in st.session_state: |
|
st.session_state.temp_pdf_path = None |
|
|
|
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf") |
|
|
|
if uploaded_file: |
|
pdf_file = uploaded_file |
|
temp_pdf_path = os.path.join(st.session_state.tmp_dir, "pdf_file") |
|
with open(temp_pdf_path, "wb") as f: |
|
f.write(pdf_file.getvalue()) |
|
st.session_state.temp_pdf_path = temp_pdf_path |
|
uploaded_file = None |
|
|
|
create_pdf_download_button(st.session_state.temp_pdf_path) |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |