File size: 1,474 Bytes
f7a13d2 f46042a f7a13d2 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
import tempfile
import streamlit as st
import os
def create_pdf_download_button(pdf_path):
# Check if the PDF file exists
if not os.path.exists(pdf_path):
st.error(f"The PDF file '{os.path.basename(pdf_path)}' was not found.")
return
# Create a download link
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):
# Read the file contents
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() |