kuroiikimono's picture
Update app.py
d7e2db0 verified
import streamlit as st
import fitz # PyMuPDF
import io
# Application title
st.title("PDF Merger with Slider Ordering 𓁨")
st.write("Upload multiple PDF files and the app will merge them into one PDF.")
# Description
st.markdown("""
1. Upload multiple PDF files
2. Use sliders to specify the order of each file
3. Click [πŸš€ Merge PDFs] to merge and then [⬇️ Download Merged PDF] to download
""")
st.video("https://youtu.be/vsREt0Jh7eo?si=5XAaL9h1wxTNJfpN")
# PDF file upload
uploaded_files = st.file_uploader(
"Select PDF files (multiple allowed)",
type="pdf",
accept_multiple_files=True
)
if uploaded_files:
# Dynamically set the maximum value for the slider
max_order = len(uploaded_files)
# Dictionary to store file order
order_dict = {}
st.subheader("πŸ”’ Specify Merge Order")
# Assign sliders to each file
cols = st.columns(1) # Display in a single column
for idx, uploaded_file in enumerate(uploaded_files):
with cols[idx % 1]: # Display files in a single column
default_order = idx + 1 # Default order is the upload order
if max_order > 1:
order = st.slider(
f"Order for {uploaded_file.name}",
min_value=1,
max_value=max_order,
value=default_order,
key=f"slider_{idx}"
)
order_dict[idx] = order # Use index as the key
# Duplicate check
unique_orders = set(order_dict.values())
if len(unique_orders) != max_order:
st.error("⚠️ Upload two or more PDFs. Duplicate order detected! Please assign unique numbers using the sliders.")
st.stop()
# Merge button
if st.button("πŸš€ Merge PDFs", type="primary"):
try:
# Sort files by specified order
sorted_files = sorted(
zip(uploaded_files, order_dict.values()), # Pair files with their order
key=lambda x: x[1] # Sort by order
)
# Create a new PDF document
merged_doc = fitz.open()
# Merge PDFs in the specified order
for uploaded_file, _ in sorted_files:
file_data = uploaded_file.read()
doc = fitz.open("pdf", file_data)
merged_doc.insert_pdf(doc)
merged_doc.subset_fonts()
# Optimize and save
output_pdf = io.BytesIO()
merged_doc.save(
output_pdf,
deflate=True,
garbage=4,
deflate_fonts=True,
use_objstms=1
)
output_pdf.seek(0)
# Download button
st.success("βœ… PDF merging completed!")
st.download_button(
label="⬇️ Download Merged PDF",
data=output_pdf,
file_name="merged.pdf",
mime="application/pdf",
help="Click to download the merged PDF"
)
except Exception as e:
st.error(f"An error occurred: {str(e)}")
else:
st.info("πŸ“ Please upload PDF files from the top section")