-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
220 lines (181 loc) · 8.69 KB
/
Copy pathapp.py
File metadata and controls
220 lines (181 loc) · 8.69 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import streamlit as st
from PyPDF2 import PdfReader, PdfWriter
from pdf2image import convert_from_bytes, exceptions
from io import BytesIO
from PIL import Image
import zipfile
from base64 import b64encode
# Set Poppler path if not in system PATH
POPPLER_PATH = r"C:\Program Files\poppler-24.07.0\Library\bin"
st.set_page_config(page_title="PDF Splitter", layout="wide")
st.title("📄 PDF Splitter by Page Ranges")
# 💡 Help Section
with st.expander("ℹ️ How to Use This App"):
st.markdown("""
- Upload a PDF file.
- Preview any page to confirm content.
- Define one or more page ranges to split.
- View a summary of your selections with preview images.
- Download each part individually or all parts as a ZIP file.
""")
st.subheader("🔧 Advanced Options")
# 🔐 Password protection
add_password = st.checkbox("Encrypt output PDFs")
pdf_password = ""
if add_password:
pdf_password = st.text_input("Enter password for PDFs", type="password")
# 📂 File upload
uploaded_file = st.file_uploader("Upload a PDF", type="pdf")
if uploaded_file is not None:
try:
# Verify file is not empty
if uploaded_file.size == 0:
st.error("Uploaded file is empty. Please upload a valid PDF file.")
st.stop()
# Read file content
pdf_bytes = uploaded_file.getvalue()
# Verify PDF content
try:
pdf_reader = PdfReader(BytesIO(pdf_bytes))
if len(pdf_reader.pages) == 0:
st.error("The PDF contains no pages. Please upload a valid PDF file.")
st.stop()
except Exception as e:
st.error(f"Failed to read PDF: {str(e)}")
st.stop()
total_pages = len(pdf_reader.pages)
st.success(f"PDF loaded successfully with {total_pages} pages.")
# 👀 Preview a page with adjustable resolution
st.subheader("Preview a Page")
preview_page = st.slider("Select a page to preview", 1, total_pages, 1)
preview_size = st.selectbox("Preview image size", ["Small", "Medium", "Large"], index=1)
size_map = {
"Small": (300, 400),
"Medium": (600, 800),
"Large": (900, 1200)
}
try:
# Convert the PDF page to image
preview_images = convert_from_bytes(
pdf_bytes,
first_page=preview_page,
last_page=preview_page,
poppler_path=POPPLER_PATH
)
if preview_images: # Check if we got any images
preview_image = preview_images[0]
# Resize for display
resized_image = preview_image.resize(size_map[preview_size])
st.image(resized_image, caption=f"Page {preview_page}", use_container_width=True)
# Create full resolution image data
img_byte_arr = BytesIO()
preview_image.save(img_byte_arr, format='PNG')
img_byte_arr = img_byte_arr.getvalue()
# Create download link
st.markdown(
f'<a href="data:image/png;base64,{b64encode(img_byte_arr).decode()}" download="page_{preview_page}.png">🔍 Download Full Resolution</a>',
unsafe_allow_html=True
)
else:
st.warning("No preview image was generated")
except exceptions.PDFPageCountError:
st.error("Unable to preview page. The PDF may be malformed or encrypted.")
except exceptions.PDFInfoNotInstalledError:
st.error("Poppler is not installed or not in PATH.")
except Exception as e:
st.error(f"Error generating preview: {str(e)}")
#
# 🔢 Define page ranges
st.subheader("Define Page Ranges to Split")
num_ranges = st.number_input("How many ranges?", min_value=1, max_value=10, value=1)
page_ranges = []
for i in range(num_ranges):
col1, col2 = st.columns(2)
with col1:
start = st.number_input(f"Start page {i+1}", min_value=1, max_value=total_pages, value=1, key=f"start_{i}")
with col2:
end = st.number_input(f"End page {i+1}", min_value=start, max_value=total_pages, value=start, key=f"end_{i}")
page_ranges.append((start, end))
# 📋 Summary with preview images
st.subheader("📋 Summary of Selected Ranges")
for i, (start, end) in enumerate(page_ranges):
st.markdown(f"**Range {i+1}: Pages {start} to {end}**")
try:
preview_images = convert_from_bytes(
pdf_bytes,
first_page=start,
last_page=end,
poppler_path=POPPLER_PATH
)
cols = st.columns(2)
with cols[0]:
preview_images[0].thumbnail((200, 300))
st.image(preview_images[0], caption=f"Start Page {start}", use_container_width=True)
with cols[1]:
preview_images[-1].thumbnail((200, 300))
st.image(preview_images[-1], caption=f"End Page {end}", use_container_width=True)
except Exception as e:
st.warning(f"Could not preview pages for range {i+1}: {e}")
st.subheader("📥 Download Options")
# 🔠 File naming format
filename_format = st.selectbox("Choose file naming format", [
"split_part_{i}_pages_{start}_to_{end}.pdf",
"range_{start}-{end}.pdf",
"part_{i}.pdf"
])
# 📄 Include summary file
include_summary = st.checkbox("Include a summary text file with page ranges")
# Initialize dictionary to store individual PDF parts
pdf_parts = {}
if st.button("✂️ Split and Prepare Downloads"):
try:
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, "w") as zipf:
summary_lines = []
for i, (start, end) in enumerate(page_ranges):
name = filename_format.format(i=i+1, start=start, end=end)
writer = PdfWriter()
for page_num in range(start - 1, end):
page = pdf_reader.pages[page_num]
writer.add_page(page)
# 🔐 Encrypt if needed
if add_password and pdf_password:
writer.encrypt(pdf_password)
part_buffer = BytesIO()
writer.write(part_buffer)
pdf_data = part_buffer.getvalue()
# Store individual PDF part for separate download
pdf_parts[name] = pdf_data
# Add to ZIP
zipf.writestr(name, pdf_data)
summary_lines.append(f"Part {i+1}: Pages {start} to {end} → {name}")
# 📄 Add summary file
if include_summary:
summary_text = "\n".join(summary_lines)
summary_text += f"\n\nPassword for encrypted PDFs: {pdf_password}" if add_password else ""
zipf.writestr("summary.txt", summary_text)
# Display download options
st.subheader("Download Options")
# Option 1: Download all parts as ZIP
st.download_button(
label="📁 Download ALL Parts as ZIP",
data=zip_buffer.getvalue(),
file_name="split_parts.zip",
mime="application/zip"
)
# Option 2: Download individual parts
st.markdown("### Download Individual Parts")
cols = st.columns(3) # Create 3 columns for better layout
for i, (name, pdf_data) in enumerate(pdf_parts.items()):
with cols[i % 3]: # Distribute buttons across columns
st.download_button(
label=f"⬇️ {name}",
data=pdf_data,
file_name=name,
mime="application/pdf",
key=f"individual_{i}"
)
except Exception as e:
st.error(f"Failed to create PDF: {str(e)}")
except Exception as e:
st.error(f"Failed to process PDF: {str(e)}")