Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 14126

Streamlit : Dynamically open multiple pdfs files in different tabs

$
0
0

I have a Streamlit application where I can upload some pdf files and then select the files I want to work on from a select box and they will be displayed in the main panel. Now instead of displaying all the selected pdfs one after the other, I wonder if it’s possible to dynamically open every selected file in a new tab with the file name as its title. Of course, if I un-select the file, the tab should disappear.

Here's what I have tried so far, but it's not working as I want. Any suggestions ?

import streamlit as stimport osfrom PyPDF2 import PdfReaderfrom io import BytesIO# Function to read PDF and return contentdef read_pdf(file_path):    # Replace with your PDF reading logic    pdf = PdfReader(file_path)    return pdf# Function to display PDF contentdef display_pdf(pdf):    num_pages = pdf.page_count    # Display navigation input for selecting a specific page    page_number = st.number_input("Enter page number", value=1, min_value=1, max_value=num_pages    )    # Display an image for the selected page    image_bytes = pdf[page_number - 1].get_pixmap().tobytes()    st.image(image_bytes, caption=f"Page {page_number} of {num_pages}")# Main Streamlit app codest.title("PDF Viewer App")# Get uploaded filesselected_files = st.file_uploader("Upload PDF files", type=["pdf"], accept_multiple_files=True)# List to store content of all pages for each fileall_files_content = []# Dictionary to store selected file contentselected_file_content = {}# Iterate over uploaded filesfor uploaded_file in selected_files:    file_content = uploaded_file.read()    temp_file_path = f"./temp/{uploaded_file.name}"    os.makedirs(os.path.dirname(temp_file_path), exist_ok=True)    with open(temp_file_path, "wb") as temp_file:        temp_file.write(file_content)    if uploaded_file.type == "application/pdf":        # Read PDF and store content        pdf = read_pdf(temp_file_path)        all_files_content.append(pdf)        # Display PDF content        selected_file_content[uploaded_file.name] = pdf        # Cleanup: Remove the temporary file        os.remove(temp_file_path)# Create tabs dynamically for each filewith st.tabs(list(selected_file_content.keys())):    for file_name, pdf in selected_file_content.items():        display_pdf(pdf)

Viewing all articles
Browse latest Browse all 14126

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>