import streamlit as st
import os
import PyPDF2
import tempfile
import shutil
from pathlib import Path
import math
import time
import subprocess
import sys
def compress_pdf(input_file, output_file, compression_level=2):
"""Compress a PDF file using Ghostscript if available, or PyPDF2 if not"""
try:
# First try using Ghostscript for better compression if available
gs_command = None
if sys.platform == 'win32':
gs_command = ['gswin64c', '-sDEVICE=pdfwrite', f'-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
else:
gs_command = ['gs', '-sDEVICE=pdfwrite', f'-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
code
result = subprocess.run(gs_command, check=True, stderr=subprocess.PIPE)
return True
except (subprocess.SubprocessError, FileNotFoundError):
# Fallback to PyPDF2 (less effective compression)
try:
reader = PyPDF2.PdfReader(input_file)
writer = PyPDF2.PdfWriter()
# Add all pages with reduced quality
for page in reader.pages:
writer.add_page(page)
# Set compression parameters
writer.add_metadata(reader.metadata)
with open(output_file, 'wb') as f_out:
writer.write(f_out)
return True
except Exception as e:
st.error(f"Compression failed: {str(e)}")
return False
def split_pdf_fast_with_compression(input_file, target_size_mb=100):
"""Split a PDF file into multiple files and compress those that exceed target size"""
# Get the total size of the input file in MB
total_size_mb = os.path.getsize(input_file) / (1024 * 1024)
code
Assistant
User
one by one is time comusimg provess
Assistant
User
Binary search on pages/chunk Medium Good Medium
Estimate avg pages/chunk + compress Fastest Medium Low write complet upadted cod efor both these
Assistant
User
Assistant
User
complte upadted code with name of files in that like .....name of orginal pdf (1) .pdf annd so on
Assistant
if total_size_mb <= target_size_mb:
st.info(f"File is already smaller than {target_size_mb}MB. No need to split.")
return []
original_filename = os.path.basename(input_file)
filename_without_ext = os.path.splitext(original_filename)[0]
# Create a temporary directory to store output files
with tempfile.TemporaryDirectory() as temp_dir:
# Open the PDF file
with open(input_file, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
total_pages = len(pdf_reader.pages)
# Calculate number of chunks needed
num_chunks = math.ceil(total_size_mb / target_size_mb)
# Calculate approximately how many pages per chunk (evenly distributed)
pages_per_chunk = math.ceil(total_pages / num_chunks)
output_files = []
# Process chunks
for chunk_number in range(1, num_chunks + 1):
start_page = (chunk_number - 1) * pages_per_chunk
end_page = min(chunk_number * pages_per_chunk, total_pages)
if start_page >= total_pages:
break
# Create a new PDF writer for this chunk
pdf_writer = PyPDF2.PdfWriter()
# Add pages to this chunk
for page_num in range(start_page, end_page):
pdf_writer.add_page(pdf_reader.pages[page_num])
# Generate output file name
output_file = os.path.join(temp_dir, f"{filename_without_ext}({chunk_number}).pdf")
# Write the PDF to the output file
with open(output_file, 'wb') as output:
pdf_writer.write(output)
# Calculate the actual size of the output file
actual_size_mb = os.path.getsize(output_file) / (1024 * 1024)
# Check if the file exceeds the target size and needs compression
if actual_size_mb > target_size_mb:
compressed_file = os.path.join(temp_dir, f"{filename_without_ext}({chunk_number})_compressed.pdf")
if compress_pdf(output_file, compressed_file):
compressed_size_mb = os.path.getsize(compressed_file) / (1024 * 1024)
# Use the compressed file if it's smaller
if compressed_size_mb < actual_size_mb:
os.replace(compressed_file, output_file)
actual_size_mb = compressed_size_mb
# Add the output file to the list
output_files.append({
'path': output_file,
'filename': f"{filename_without_ext}({chunk_number}).pdf",
'size_mb': actual_size_mb,
'pages': end_page - start_page,
'compressed': actual_size_mb > target_size_mb
})
# Copy files to a location outside the temporary directory
permanent_files = []
output_dir = os.path.dirname(input_file)
for file_info in output_files:
dest_path = os.path.join(output_dir, file_info['filename'])
shutil.copy2(file_info['path'], dest_path)
file_info['path'] = dest_path
permanent_files.append(file_info)
return permanent_files
def main():
st.title("Large PDF Splitter")
st.write("Upload a large PDF file to split it into smaller chunks")
code
max_chunk_size = st.slider("Maximum size per chunk (MB)", min_value=10, max_value=500, value=100, step=10)
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
if uploaded_file is not None:
# Create a temporary file to save the uploaded file
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
with st.spinner("Processing uploaded file..."):
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
# Preserve the original filename
original_filename = uploaded_file.name
file_size_mb = os.path.getsize(tmp_file_path) / (1024 * 1024)
st.write(f"Uploaded file: {original_filename}")
st.write(f"File size: {file_size_mb:.2f} MB")
if st.button("Split File"):
if file_size_mb <= max_chunk_size:
st.warning(f"The file is already smaller than {max_chunk_size}MB. No need to split.")
else:
start_time = time.time()
with st.spinner(f"Splitting {original_filename} into chunks and compressing if needed..."):
output_files = split_pdf_fast_with_compression(tmp_file_path, max_chunk_size)
end_time = time.time()
if output_files:
processing_time = end_time - start_time
st.success(f"Successfully split into {len(output_files)} files in {processing_time:.2f} seconds!")
# Show file size distribution
st.write("### Generated Files:")
for file_info in output_files:
col1, col2 = st.columns([3, 1])
with col1:
status = " (compressed)" if file_info.get('compressed', False) else ""
st.write(f"**{file_info['filename']}** ({file_info['size_mb']:.2f} MB{status}, {file_info['pages']} pages)")
with col2:
with open(file_info['path'], 'rb') as f:
st.download_button(
label=f"Download",
data=f.read(),
file_name=file_info['filename'],
mime="application/pdf"
)
else:
st.error("Error splitting the file.")
# Clean up the temporary file after processing
os.unlink(tmp_file_path)
if name == "main":
main() THIS codes returns me tmpui2brstt(1).pdf (48.31 MB, 325 pages)
tmpui2brstt(3).pdf (38.57 MB, 323 pages) but i wnated the size of one pdf to be max 100mb ...so aftre spliiting do whatever possible but i needed 100mb not more than taht....either compress the sixze of splited pdf or other
Your current approach splits the original PDF roughly by pages count (equal division) and then compresses the resulting chunks if they still exceed the target size (max_chunk_size), but the compression is not guaranteed to bring the PDF under the desired size limit. This is why some chunks still exceed the 100MB target after compression.
How to achieve strict max size per chunk?
Challenges:
PDF size doesn't scale linearly with page count.
Pages with heavy images can cause chunks to be larger than expected.
Compression effects are variable and cannot guarantee a size below the threshold.
PyPDF2 doesn't support compressing content streams deeply.
Suggested approach:
Iterative page adding per chunk until size limit reached.
Instead of splitting by fixed number of pages, add pages one by one, check chunk size after adding each page. Once exceeding 100 MB, finalize that chunk and start a new chunk.
Compress each chunk immediately after building it if it exceeds size limit.
Implementation details:
Read pages one by one.
Build chunks incrementally, writing each to a temporary file after adding each page.
Check current chunk size; if close or above target, compress and then finalize chunk.
Move to next chunk.
Revised code snippet for split_pdf_fast_with_compression implementing incremental chunking by size:
python
def split_pdf_fast_with_compression(input_file, target_size_mb=100):
original_filename = os.path.basename(input_file)
filename_without_ext = os.path.splitext(original_filename)[0]
with tempfile.TemporaryDirectory() as temp_dir:
with open(input_file, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
total_pages = len(pdf_reader.pages)
output_files = []
current_writer = PyPDF2.PdfWriter()
chunk_number = 1
for page_number in range(total_pages):
current_writer.add_page(pdf_reader.pages[page_number])
# Write current chunk to temp file to check size
current_chunk_path = os.path.join(temp_dir, f"{filename_without_ext}({chunk_number}).pdf")
with open(current_chunk_path, 'wb') as temp_out:
current_writer.write(temp_out)
size_mb = os.path.getsize(current_chunk_path) / (1024 * 1024)
# If adding this page exceeds target size or last page reached, finalize chunk
is_last_page = (page_number == total_pages - 1)
if size_mb >= target_size_mb or is_last_page:
# Compress if necessary
if size_mb > target_size_mb:
compressed_path = os.path.join(temp_dir, f"{filename_without_ext}({chunk_number})_compressed.pdf")
if compress_pdf(current_chunk_path, compressed_path):
compressed_size_mb = os.path.getsize(compressed_path) / (1024 * 1024)
if compressed_size_mb < size_mb:
os.replace(compressed_path, current_chunk_path)
size_mb = compressed_size_mb
output_files.append({
'path': current_chunk_path,
'filename': f"{filename_without_ext}({chunk_number}).pdf",
'size_mb': size_mb,
'pages': len(current_writer.pages),
'compressed': size_mb > target_size_mb
})
# Prepare for next chunk if not last page
if not is_last_page:
chunk_number += 1
current_writer = PyPDF2.PdfWriter()
# Copy files to permanent location (same directory as input file)
output_dir = os.path.dirname(input_file)
permanent_files = []
for file_info in output_files:
dest_path = os.path.join(output_dir, file_info['filename'])
shutil.copy2(file_info['path'], dest_path)
file_info['path'] = dest_path
permanent_files.append(file_info)
return permanent_files
Explanation:
Pages added one by one.
After each page, the current chunk is saved to a temporary file.
We check the file size, and if exceeds target_size_mb or is the last page, chunk is finalized.
If the chunk is oversized, compress with Ghostscript (or fallback).
Then start a new chunk.
At the end, temporary files are copied to the permanent folder.
Important notes:
This approach writes the intermediate PDF for every page added to check the file size, which can be slower.
Compression might still not always guarantee below the limit, but it's an improved heuristic.
Ghostscript must be installed and accessible via terminal (gs or gswin64c) for compression to be effective.
You can adjust -dPDFSETTINGS in Ghostscript command (/screen, /ebook, /printer, /prepress) to adjust compression aggressiveness.
Summary:
Instead of fixed pages per chunk, iterate and check size per page added.
Compress chunks that exceed size.
This should better ensure that no chunk exceeds target size (~100MB).
If you want, I can integrate this modified function into your full Streamlit app code. Would you like me to do that?
Yes, you are right — adding pages one by one, writing out the PDF repeatedly to check file size is time-consuming, especially for large PDFs.
Alternative Approaches to Balance Speed and Size Control
If speed is critical and you want to avoid per-page checks, here are some strategies you can consider:
1. Use Binary Search on chunk size (number of pages per chunk)
Instead of naive equal division or one-by-one page adding, you can:
Guess an initial number of pages per chunk (e.g., total_pages / target_chunks).
Write chunk with that number of pages.
Check size:
If chunk size > target size → reduce number of pages per chunk.
Else if chunk size << target size → increase number of pages per chunk.
Repeat until chunk size is close to target size.
Proceed for next chunk.
This binary search method minimizes writing files many times (at worst about log2(total_pages) times per chunk) instead of once per page.
2. Use Metadata or Heuristic to estimate page size
If a chunk is still oversized, reduce pages per chunk only for the next chunks (adaptive approach).
3. Use Ghostscript directly to downsample and compress
Sometimes it’s easiest to split by pages and then compress all chunks aggressively with Ghostscript /screen or /ebook quality.
If the compression is aggressive enough, chunk sizes will likely fall below limit.
Downside:
Lower quality PDFs.
Compression time is still a factor.
4. Use a hybrid approach: adaptive split + compression
Calculate pages per chunk by estimate.
Split chunks.
Compress all chunks.
If some still exceed target, reduce pages per chunk and repeat splitting only for the problematic chunks.
Here's an example to implement strategy (1) — binary search to find pages per chunk:
python
Advantages:
Reduces excessive writes.
Usually only O(log N) writes per chunk.
Gives tight control over chunk sizes.
Disadvantages:
Still requires multiple writes per chunk during binary search (but much faster than per page).
Adding compression step only once per chunk.
If PDFs have very uneven pages (some huge and some tiny), might be slower.
Summary of recommendations:
Approach
Speed
Quality control
Complexity
Add pages one-by-one
Slowest
Best
Medium
Binary search on pages/chunk
Medium
Good
Medium
Estimate avg pages/chunk + compress
Fastest
Medium
Low
If you want, I can provide a full modified Streamlit code version with binary search chunking for you. Would you like me to do that?
Sure! Below are two complete versions of your Streamlit app with updated splitting logic:
1) Fastest version: Estimate average pages per chunk + compress
This version is fast and simple:
Calculate average page size
Use it to split into chunks by pages
Compress each chunk if it exceeds max size
Code for estimate avg pages/chunk + compress version:
python
import streamlit as st
import os
import PyPDF2
import tempfile
import shutil
from pathlib import Path
import math
import time
import subprocess
import sys
def compress_pdf(input_file, output_file, compression_level=2):
"""Compress a PDF file using Ghostscript if available, or PyPDF2 if not"""
try:
# Ghostscript command (adjust -dPDFSETTINGS for compression quality)
gs_command = None
if sys.platform == 'win32':
gs_command = ['gswin64c', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
else:
gs_command = ['gs', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
subprocess.run(gs_command, check=True, stderr=subprocess.PIPE)
return True
except (subprocess.SubprocessError, FileNotFoundError):
# Fallback to PyPDF2 (less effective compression)
try:
reader = PyPDF2.PdfReader(input_file)
writer = PyPDF2.PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.add_metadata(reader.metadata)
with open(output_file, 'wb') as f_out:
writer.write(f_out)
return True
except Exception as e:
st.error(f"Compression failed: {str(e)}")
return False
def split_pdf_estimate_avg(input_file, target_size_mb=100):
original_filename = os.path.basename(input_file)
filename_without_ext = os.path.splitext(original_filename)[0]
with open(input_file, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
total_pages = len(pdf_reader.pages)
total_size_mb = os.path.getsize(input_file) / (1024*1024)
avg_page_size = total_size_mb / total_pages
pages_per_chunk = max(1, math.floor(target_size_mb / avg_page_size))
num_chunks = math.ceil(total_pages / pages_per_chunk)
output_files = []
with tempfile.TemporaryDirectory() as temp_dir:
for chunk_num in range(num_chunks):
start = chunk_num * pages_per_chunk
end = min((chunk_num + 1) * pages_per_chunk, total_pages)
pdf_writer = PyPDF2.PdfWriter()
for i in range(start, end):
pdf_writer.add_page(pdf_reader.pages[i])
output_file = os.path.join(temp_dir, f"{filename_without_ext}({chunk_num + 1}).pdf")
with open(output_file, 'wb') as f_out:
pdf_writer.write(f_out)
actual_size_mb = os.path.getsize(output_file) / (1024*1024)
# Compress if oversized
if actual_size_mb > target_size_mb:
compressed_file = os.path.join(temp_dir, f"{filename_without_ext}({chunk_num + 1})_compressed.pdf")
if compress_pdf(output_file, compressed_file):
compressed_size_mb = os.path.getsize(compressed_file) / (1024*1024)
if compressed_size_mb < actual_size_mb:
os.replace(compressed_file, output_file)
actual_size_mb = compressed_size_mb
output_files.append({
'path': output_file,
'filename': f"{filename_without_ext}({chunk_num + 1}).pdf",
'size_mb': actual_size_mb,
'pages': end - start,
'compressed': actual_size_mb > target_size_mb
})
# Copy files outside temp folder
output_dir = os.path.dirname(input_file)
permanent_files = []
for file_info in output_files:
dest_path = os.path.join(output_dir, file_info['filename'])
shutil.copy2(file_info['path'], dest_path)
file_info['path'] = dest_path
permanent_files.append(file_info)
return permanent_files
def main():
st.title("Large PDF Splitter - Avg Pages per Chunk Method")
st.write("Upload a large PDF file to split it into smaller chunks by estimating average page size")
max_chunk_size = st.slider("Maximum size per chunk (MB)", min_value=10, max_value=500, value=100, step=10)
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
if uploaded_file:
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
with st.spinner("Processing uploaded file..."):
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
original_filename = uploaded_file.name
file_size_mb = os.path.getsize(tmp_file_path) / (1024 * 1024)
st.write(f"Uploaded file: {original_filename}")
st.write(f"File size: {file_size_mb:.2f} MB")
if st.button("Split File"):
if file_size_mb <= max_chunk_size:
st.warning(f"The file is already smaller than {max_chunk_size}MB. No need to split.")
else:
start_time = time.time()
with st.spinner(f"Splitting {original_filename} into chunks..."):
output_files = split_pdf_estimate_avg(tmp_file_path, max_chunk_size)
end_time = time.time()
if output_files:
processing_time = end_time - start_time
st.success(f"Successfully split into {len(output_files)} files in {processing_time:.2f} seconds!")
st.write("### Generated Files:")
for file_info in output_files:
col1, col2 = st.columns([3, 1])
with col1:
status = " (compressed)" if file_info.get('compressed', False) else ""
st.write(f"**{file_info['filename']}** ({file_info['size_mb']:.2f} MB{status}, {file_info['pages']} pages)")
with col2:
with open(file_info['path'], 'rb') as f:
st.download_button(
label="Download",
data=f.read(),
file_name=file_info['filename'],
mime="application/pdf"
)
else:
st.error("Error splitting the file.")
os.unlink(tmp_file_path)
if __name__ == "__main__":
main()
2) Medium speed/quality: Binary search on pages per chunk
This version applies binary search per chunk to find max pages for chunk ≤ target size, compressing if needed.
Complete code for the binary search splitting version:
python
How to use:
Save either code into a .py file.
Run with streamlit run your_file.py.
Upload a large PDF, select your desired max chunk size.
Click Split File to perform splitting and compression.
Download the resulting chunks.
Note:
Ghostscript must be installed and accessible as gs (Linux/macOS) or gswin64c (Windows) for compression.
Compression quality can be adjusted by changing -dPDFSETTINGS.
Options:
/screen (lowest quality, smallest size)
/ebook (medium quality, reasonable size)
/printer (higher quality)
/prepress (highest quality, largest size)
If you want me to help you customize further or combine them to offer both methods selectable in one app just let me know!
import streamlit as st
import os
import PyPDF2
import tempfile
import shutil
from pathlib import Path
import time
import subprocess
import sys
def compress_pdf(input_file, output_file, compression_level=2):
"""Compress a PDF file using Ghostscript if available, or PyPDF2 if not"""
try:
gs_command = None
if sys.platform == 'win32':
gs_command = ['gswin64c', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
else:
gs_command = ['gs', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
subprocess.run(gs_command, check=True, stderr=subprocess.PIPE)
return True
except (subprocess.SubprocessError, FileNotFoundError):
try:
reader = PyPDF2.PdfReader(input_file)
writer = PyPDF2.PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.add_metadata(reader.metadata)
with open(output_file, 'wb') as f_out:
writer.write(f_out)
return True
except Exception as e:
st.error(f"Compression failed: {str(e)}")
return False
def get_chunk_size(input_file, start_page, num_pages):
"""Create a PDF chunk from start_page with num_pages pages and return its size and file path"""
pdf_reader = PyPDF2.PdfReader(open(input_file, 'rb'))
pdf_writer = PyPDF2.PdfWriter()
code
total_pages = len(pdf_reader.pages)
end_page = min(start_page + num_pages, total_pages)
for i in range(start_page, end_page):
pdf_writer.add_page(pdf_reader.pages[i])
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tf:
pdf_writer.write(tf)
temp_path = tf.name
size_mb = os.path.getsize(temp_path) / (1024*1024)
return size_mb, temp_path, end_page
def main():
st.title("Large PDF Splitter - Binary Search Method")
st.write("Upload a large PDF file to split it into chunks by binary search to fit size limit")
code
max_chunk_size = st.slider("Maximum size per chunk (MB)", min_value=10, max_value=500, value=100, step=10)
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
if uploaded_file:
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
with st.spinner("Processing uploaded file..."):
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
original_filename = uploaded_file.name
file_size_mb = os.path.getsize(tmp_file_path) / (1024 * 1024)
st.write(f"Uploaded file: {original_filename}")
st.write(f"File size: {file_size_mb:.2f} MB")
if st.button("Split File"):
if file_size_mb <= max_chunk_size:
st.warning(f"The file is already smaller than {max_chunk_size}MB. No need to split.")
else:
start_time = time.time()
with st.spinner(f"Splitting {original_filename} into chunks..."):
output_files = split_pdf_binary_search(tmp_file_path, max_chunk_size)
end_time = time.time()
if output_files:
processing_time = end_time - start_time
st.success(f"Successfully split into {len(output_files)} files in {processing_time:.2f} seconds!")
st.write("### Generated Files:")
for file_info in output_files:
col1, col2 = st.columns([3, 1])
with col1:
status = " (compressed)" if file_info.get('compressed', False) else ""
st.write(f"**{file_info['filename']}** ({file_info['size_mb']:.2f} MB{status}, {file_info['pages']} pages)")
with col2:
with open(file_info['path'], 'rb') as f:
st.download_button(
label="Download",
data=f.read(),
file_name=file_info['filename'],
mime="application/pdf"
)
else:
st.error("Error splitting the file.")
os.unlink(tmp_file_path)
if name == "main":
main() in tis add a single download button to downolad all the spllietd pdfs in one
To add a single download button for all split PDFs combined into one ZIP archive, you can do the following:
After splitting, create a temporary ZIP archive containing all split PDF files.
Provide a single download button linked to this ZIP file.
Here's how you can modify your main() function and related code to add this:
Import io and zipfile.
After splitting is done, create a ZIP archive in a temporary file.
Use st.download_button for the ZIP.
Complete modifications inside your main() function:
python
import io
import zipfile
def main():
st.title("Large PDF Splitter - Binary Search Method")
st.write("Upload a large PDF file to split it into chunks by binary search to fit size limit")
max_chunk_size = st.slider("Maximum size per chunk (MB)", min_value=10, max_value=500, value=100, step=10)
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
if uploaded_file:
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
with st.spinner("Processing uploaded file..."):
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
original_filename = uploaded_file.name
file_size_mb = os.path.getsize(tmp_file_path) / (1024 * 1024)
st.write(f"Uploaded file: {original_filename}")
st.write(f"File size: {file_size_mb:.2f} MB")
if st.button("Split File"):
if file_size_mb <= max_chunk_size:
st.warning(f"The file is already smaller than {max_chunk_size}MB. No need to split.")
else:
start_time = time.time()
with st.spinner(f"Splitting {original_filename} into chunks..."):
output_files = split_pdf_binary_search(tmp_file_path, max_chunk_size)
end_time = time.time()
if output_files:
processing_time = end_time - start_time
st.success(f"Successfully split into {len(output_files)} files in {processing_time:.2f} seconds!")
st.write("### Generated Files:")
for file_info in output_files:
col1, col2 = st.columns([3, 1])
with col1:
status = " (compressed)" if file_info.get('compressed', False) else ""
st.write(f"**{file_info['filename']}** ({file_info['size_mb']:.2f} MB{status}, {file_info['pages']} pages)")
with col2:
with open(file_info['path'], 'rb') as f:
st.download_button(
label="Download",
data=f.read(),
file_name=file_info['filename'],
mime="application/pdf"
)
# Create a ZIP archive of all split files for single download
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w") as zip_file:
for file_info in output_files:
zip_file.write(file_info['path'], arcname=file_info['filename'])
zip_buffer.seek(0)
st.download_button(
label="Download All as ZIP",
data=zip_buffer,
file_name=f"{os.path.splitext(original_filename)[0]}_split_files.zip",
mime="application/zip"
)
else:
st.error("Error splitting the file.")
os.unlink(tmp_file_path)
Explanation:
io.BytesIO() creates an in-memory buffer for the ZIP file (no disk write needed).
zipfile.ZipFile writes all PDF chunks into the ZIP archive with their filenames.
After creating the ZIP, the buffer is rewound (seek(0)), then passed to st.download_button.
The user sees an extra button Download All as ZIP to get everything in one download.
If you want a fully integrated script with this included, or want me to adapt it also to the other method, just ask!
Certainly! Below is the full updated Streamlit app code with:
Your binary search split + compression logic.
Split files named as OriginalFileName (1).pdf, OriginalFileName (2).pdf, etc. (space before and after parentheses).
Individual download buttons per split PDF.
One single ZIP download button containing all split PDFs.
Proper temp file cleanup.
python
import streamlit as st
import os
import PyPDF2
import tempfile
import shutil
import time
import subprocess
import sys
import io
import zipfile
def compress_pdf(input_file, output_file, compression_level=2):
"""Compress a PDF file using Ghostscript if available, or PyPDF2 if not"""
try:
if sys.platform == 'win32':
gs_command = ['gswin64c', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
else:
gs_command = ['gs', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
subprocess.run(gs_command, check=True, stderr=subprocess.PIPE)
return True
except (subprocess.SubprocessError, FileNotFoundError):
try:
reader = PyPDF2.PdfReader(input_file)
writer = PyPDF2.PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.add_metadata(reader.metadata)
with open(output_file, 'wb') as f_out:
writer.write(f_out)
return True
except Exception as e:
st.error(f"Compression failed: {str(e)}")
return False
def get_chunk_size(input_file, start_page, num_pages):
"""Create a PDF chunk from start_page with num_pages pages and return its size and file path"""
pdf_reader = PyPDF2.PdfReader(open(input_file, 'rb'))
pdf_writer = PyPDF2.PdfWriter()
total_pages = len(pdf_reader.pages)
end_page = min(start_page + num_pages, total_pages)
for i in range(start_page, end_page):
pdf_writer.add_page(pdf_reader.pages[i])
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tf:
pdf_writer.write(tf)
temp_path = tf.name
size_mb = os.path.getsize(temp_path) / (1024*1024)
return size_mb, temp_path, end_page
def split_pdf_binary_search(input_file, target_size_mb=100):
pdf_reader = PyPDF2.PdfReader(open(input_file, 'rb'))
total_pages = len(pdf_reader.pages)
original_filename = os.path.basename(input_file)
filename_without_ext = os.path.splitext(original_filename)[0]
output_files = []
chunk_number = 1
current_page = 0
while current_page < total_pages:
low = 1
high = total_pages - current_page
best_num_pages = low
best_temp_path = None
best_size = None
# Binary search for max pages fitting size limit
while low <= high:
mid = (low + high) // 2
size_mb, temp_path, _ = get_chunk_size(input_file, current_page, mid)
if size_mb <= target_size_mb:
best_num_pages = mid
best_size = size_mb
if best_temp_path:
try:
os.unlink(best_temp_path)
except:
pass
best_temp_path = temp_path
low = mid + 1
else:
try:
os.unlink(temp_path)
except:
pass
high = mid - 1
# Compress if oversized
compressed_path = best_temp_path.replace('.pdf', '_compressed.pdf')
if best_size > target_size_mb:
if compress_pdf(best_temp_path, compressed_path):
compressed_size_mb = os.path.getsize(compressed_path) / (1024*1024)
if compressed_size_mb < best_size:
try:
os.unlink(best_temp_path)
except:
pass
best_temp_path = compressed_path
best_size = compressed_size_mb
else:
try:
os.unlink(compressed_path)
except:
pass
output_files.append({
'path': best_temp_path,
'filename': f"{filename_without_ext} ({chunk_number}).pdf",
'size_mb': best_size,
'pages': best_num_pages,
'compressed': best_size > target_size_mb
})
chunk_number += 1
current_page += best_num_pages
# Copy to permanent folder, usually the input file folder
output_dir = os.path.dirname(input_file)
permanent_files = []
for file_info in output_files:
dest_path = os.path.join(output_dir, file_info['filename'])
shutil.copy2(file_info['path'], dest_path)
try:
os.unlink(file_info['path'])
except:
pass
file_info['path'] = dest_path
permanent_files.append(file_info)
return permanent_files
def main():
st.title("Large PDF Splitter - Binary Search Method")
st.write("Upload a large PDF file to split it into chunks by binary search to fit size limit")
max_chunk_size = st.slider("Maximum size per chunk (MB)", min_value=10, max_value=500, value=100, step=10)
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
if uploaded_file:
# Save uploaded file temporarily
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
with st.spinner("Processing uploaded file..."):
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
original_filename = uploaded_file.name
file_size_mb = os.path.getsize(tmp_file_path) / (1024 * 1024)
st.write(f"Uploaded file: {original_filename}")
st.write(f"File size: {file_size_mb:.2f} MB")
if st.button("Split File"):
if file_size_mb <= max_chunk_size:
st.warning(f"The file is already smaller than {max_chunk_size}MB. No need to split.")
else:
start_time = time.time()
with st.spinner(f"Splitting {original_filename} into chunks..."):
output_files = split_pdf_binary_search(tmp_file_path, max_chunk_size)
end_time = time.time()
if output_files:
processing_time = end_time - start_time
st.success(f"Successfully split into {len(output_files)} files in {processing_time:.2f} seconds!")
st.write("### Generated Files:")
for file_info in output_files:
col1, col2 = st.columns([3, 1])
with col1:
status = " (compressed)" if file_info.get('compressed', False) else ""
st.write(f"**{file_info['filename']}** ({file_info['size_mb']:.2f} MB{status}, {file_info['pages']} pages)")
with col2:
with open(file_info['path'], 'rb') as f:
st.download_button(
label="Download",
data=f.read(),
file_name=file_info['filename'],
mime="application/pdf"
)
# Create ZIP for all split files
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w") as zip_file:
for file_info in output_files:
zip_file.write(file_info['path'], arcname=file_info['filename'])
zip_buffer.seek(0)
st.download_button(
label="Download All as ZIP",
data=zip_buffer,
file_name=f"{os.path.splitext(original_filename)[0]}_split_files.zip",
mime="application/zip"
)
else:
st.error("Error splitting the file.")
# Clean up uploaded temp file
try:
os.unlink(tmp_file_path)
except:
pass
if __name__ == "__main__":
main()
Explanation of the changes:
Chunk filenames have spaces around the parentheses: "OriginalFileName (1).pdf".
In the UI, after showing each chunk file with its download button, a single "Download All as ZIP" button is shown.
ZIP is created in-memory to avoid additional temporary files.
Temporary chunk files cleaned up after copying.
Uploaded file is also cleaned up.
How to run:
Save this as pdf_splitter_streamlit.py.
Run: streamlit run pdf_splitter_streamlit.py.
Upload your PDF, select max chunk size, click Split File.
Download each chunk individually or all at once from ZIP.
If you want me to help with the other method or any other features, just say!
Dataset releases
Not yet included in a published release.
def get_chunk_size(input_file, start_page, num_pages):
"""Helper: create a PDF chunk from start_page with num_pages and return its file size"""
pdf_reader = PyPDF2.PdfReader(open(input_file, 'rb'))
pdf_writer = PyPDF2.PdfWriter()
total_pages = len(pdf_reader.pages)
end_page = min(start_page + num_pages, total_pages)
for i in range(start_page, end_page):
pdf_writer.add_page(pdf_reader.pages[i])
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tf:
pdf_writer.write(tf)
temp_path = tf.name
size_mb = os.path.getsize(temp_path) / (1024*1024)
return size_mb, temp_path, end_page
def split_pdf_binary_search(input_file, target_size_mb=100):
pdf_reader = PyPDF2.PdfReader(open(input_file, 'rb'))
total_pages = len(pdf_reader.pages)
original_filename = os.path.basename(input_file)
filename_without_ext = os.path.splitext(original_filename)[0]
output_files = []
chunk_number = 1
current_page = 0
while current_page < total_pages:
low = 1
high = total_pages - current_page
best_num_pages = low
best_temp_path = None
best_size = None
# Binary search for max pages fitting in target size
while low <= high:
mid = (low + high) // 2
size_mb, temp_path, _ = get_chunk_size(input_file, current_page, mid)
if size_mb <= target_size_mb:
best_num_pages = mid
best_size = size_mb
if best_temp_path:
os.unlink(best_temp_path) # delete previous best temp
best_temp_path = temp_path
low = mid + 1
else:
os.unlink(temp_path)
high = mid - 1
# Compress chunk if needed
compressed_path = best_temp_path.replace('.pdf', '_compressed.pdf')
if best_size > target_size_mb:
if compress_pdf(best_temp_path, compressed_path):
compressed_size_mb = os.path.getsize(compressed_path) / (1024*1024)
if compressed_size_mb < best_size:
os.unlink(best_temp_path)
best_temp_path = compressed_path
best_size = compressed_size_mb
else:
os.unlink(compressed_path)
# Save final chunk info
output_files.append({
'path': best_temp_path,
'filename': f"{filename_without_ext}({chunk_number}).pdf",
'size_mb': best_size,
'pages': best_num_pages,
'compressed': best_size > target_size_mb
})
current_page += best_num_pages
chunk_number += 1
# Move files from temp to input directory
output_dir = os.path.dirname(input_file)
permanent_files = []
for file_info in output_files:
dest_path = os.path.join(output_dir, file_info['filename'])
shutil.copy2(file_info['path'], dest_path)
os.unlink(file_info['path'])
file_info['path'] = dest_path
permanent_files.append(file_info)
return permanent_files
import streamlit as st
import os
import PyPDF2
import tempfile
import shutil
from pathlib import Path
import time
import subprocess
import sys
def compress_pdf(input_file, output_file, compression_level=2):
"""Compress a PDF file using Ghostscript if available, or PyPDF2 if not"""
try:
gs_command = None
if sys.platform == 'win32':
gs_command = ['gswin64c', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
else:
gs_command = ['gs', '-sDEVICE=pdfwrite', '-dPDFSETTINGS=/ebook',
'-dCompatibilityLevel=1.4', '-dNOPAUSE', '-dQUIET', '-dBATCH',
f'-sOutputFile={output_file}', input_file]
subprocess.run(gs_command, check=True, stderr=subprocess.PIPE)
return True
except (subprocess.SubprocessError, FileNotFoundError):
try:
reader = PyPDF2.PdfReader(input_file)
writer = PyPDF2.PdfWriter()
for page in reader.pages:
writer.add_page(page)
writer.add_metadata(reader.metadata)
with open(output_file, 'wb') as f_out:
writer.write(f_out)
return True
except Exception as e:
st.error(f"Compression failed: {str(e)}")
return False
def get_chunk_size(input_file, start_page, num_pages):
"""Create a PDF chunk from start_page with num_pages pages and return its size and file path"""
pdf_reader = PyPDF2.PdfReader(open(input_file, 'rb'))
pdf_writer = PyPDF2.PdfWriter()
total_pages = len(pdf_reader.pages)
end_page = min(start_page + num_pages, total_pages)
for i in range(start_page, end_page):
pdf_writer.add_page(pdf_reader.pages[i])
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tf:
pdf_writer.write(tf)
temp_path = tf.name
size_mb = os.path.getsize(temp_path) / (1024*1024)
return size_mb, temp_path, end_page
def split_pdf_binary_search(input_file, target_size_mb=100):
pdf_reader = PyPDF2.PdfReader(open(input_file, 'rb'))
total_pages = len(pdf_reader.pages)
original_filename = os.path.basename(input_file)
filename_without_ext = os.path.splitext(original_filename)[0]
output_files = []
chunk_number = 1
current_page = 0
while current_page < total_pages:
low = 1
high = total_pages - current_page
best_num_pages = low
best_temp_path = None
best_size = None
# Binary search for max pages fitting size
while low <= high:
mid = (low + high) // 2
size_mb, temp_path, _ = get_chunk_size(input_file, current_page, mid)
if size_mb <= target_size_mb:
best_num_pages = mid
best_size = size_mb
if best_temp_path:
os.unlink(best_temp_path)
best_temp_path = temp_path
low = mid + 1
else:
os.unlink(temp_path)
high = mid - 1
# Compress if oversized
compressed_path = best_temp_path.replace('.pdf', '_compressed.pdf')
if best_size > target_size_mb:
if compress_pdf(best_temp_path, compressed_path):
compressed_size_mb = os.path.getsize(compressed_path) / (1024*1024)
if compressed_size_mb < best_size:
os.unlink(best_temp_path)
best_temp_path = compressed_path
best_size = compressed_size_mb
else:
os.unlink(compressed_path)
output_files.append({
'path': best_temp_path,
'filename': f"{filename_without_ext}({chunk_number}).pdf",
'size_mb': best_size,
'pages': best_num_pages,
'compressed': best_size > target_size_mb
})
chunk_number += 1
current_page += best_num_pages
# Move files to permanent location
output_dir = os.path.dirname(input_file)
permanent_files = []
for file_info in output_files:
dest_path = os.path.join(output_dir, file_info['filename'])
shutil.copy2(file_info['path'], dest_path)
os.unlink(file_info['path'])
file_info['path'] = dest_path
permanent_files.append(file_info)
return permanent_files
def main():
st.title("Large PDF Splitter - Binary Search Method")
st.write("Upload a large PDF file to split it into chunks by binary search to fit size limit")
max_chunk_size = st.slider("Maximum size per chunk (MB)", min_value=10, max_value=500, value=100, step=10)
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
if uploaded_file:
with tempfile.NamedTemporaryFile(delete=False, suffix='.pdf') as tmp_file:
with st.spinner("Processing uploaded file..."):
tmp_file.write(uploaded_file.getvalue())
tmp_file_path = tmp_file.name
original_filename = uploaded_file.name
file_size_mb = os.path.getsize(tmp_file_path) / (1024 * 1024)
st.write(f"Uploaded file: {original_filename}")
st.write(f"File size: {file_size_mb:.2f} MB")
if st.button("Split File"):
if file_size_mb <= max_chunk_size:
st.warning(f"The file is already smaller than {max_chunk_size}MB. No need to split.")
else:
start_time = time.time()
with st.spinner(f"Splitting {original_filename} into chunks..."):
output_files = split_pdf_binary_search(tmp_file_path, max_chunk_size)
end_time = time.time()
if output_files:
processing_time = end_time - start_time
st.success(f"Successfully split into {len(output_files)} files in {processing_time:.2f} seconds!")
st.write("### Generated Files:")
for file_info in output_files:
col1, col2 = st.columns([3, 1])
with col1:
status = " (compressed)" if file_info.get('compressed', False) else ""
st.write(f"**{file_info['filename']}** ({file_info['size_mb']:.2f} MB{status}, {file_info['pages']} pages)")
with col2:
with open(file_info['path'], 'rb') as f:
st.download_button(
label="Download",
data=f.read(),
file_name=file_info['filename'],
mime="application/pdf"
)
else:
st.error("Error splitting the file.")
os.unlink(tmp_file_path)
if __name__ == "__main__":
main()