File size: 3,281 Bytes
71dce37
 
 
 
 
4431e63
71dce37
b2e1369
71dce37
 
 
 
 
 
 
d7e2db0
 
71dce37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
741ad03
71dce37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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")