themanas021 commited on
Commit
39d7252
·
verified ·
1 Parent(s): 161752b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PyPDF2 import PdfReader, PdfWriter
3
+
4
+ def split_pdf(input_file, output_files_with_ranges):
5
+ """
6
+ Splits a PDF into multiple PDFs based on specified page ranges.
7
+
8
+ Parameters:
9
+ input_file (str): Path to the input PDF file.
10
+ output_files_with_ranges (list of tuples): Each tuple contains the output filename and the page range (start, end).
11
+ Example: [("output1.pdf", (1, 3)), ("output2.pdf", (4, 6))]
12
+
13
+ Returns:
14
+ None
15
+ """
16
+ try:
17
+ reader = PdfReader(input_file)
18
+
19
+ for output_file, page_range in output_files_with_ranges:
20
+ writer = PdfWriter()
21
+ start, end = page_range
22
+
23
+ # Add specified page range to writer
24
+ for page_num in range(start - 1, end):
25
+ if 0 <= page_num < len(reader.pages):
26
+ writer.add_page(reader.pages[page_num])
27
+ else:
28
+ raise ValueError(f"Page number {page_num + 1} out of range for input file.")
29
+
30
+ # Write the output file
31
+ with open(output_file, "wb") as f:
32
+ writer.write(f)
33
+
34
+ st.success("PDF split successfully!")
35
+ except Exception as e:
36
+ st.error(f"An error occurred: {e}")
37
+
38
+ # Streamlit app
39
+ st.title("PDF Splitter App")
40
+
41
+ uploaded_file = st.file_uploader("Upload a PDF file", type="pdf")
42
+ if uploaded_file:
43
+ input_pdf_path = f"uploaded_{uploaded_file.name}"
44
+ with open(input_pdf_path, "wb") as f:
45
+ f.write(uploaded_file.read())
46
+
47
+ reader = PdfReader(input_pdf_path)
48
+ total_pages = len(reader.pages)
49
+ st.write(f"The uploaded PDF has {total_pages} pages.")
50
+
51
+ num_splits = st.number_input("How many splits do you want?", min_value=1, max_value=total_pages, step=1, value=1)
52
+
53
+ output_files_with_ranges = []
54
+ for i in range(num_splits):
55
+ st.write(f"### Split {i + 1}")
56
+ start = st.number_input(f"Start page for split {i + 1}", min_value=1, max_value=total_pages, step=1, value=1, key=f"start_{i}")
57
+ end = st.number_input(f"End page for split {i + 1}", min_value=1, max_value=total_pages, step=1, value=1, key=f"end_{i}")
58
+ output_filename = st.text_input(f"Output filename for split {i + 1}", value=f"PDF_Part{i + 1}.pdf", key=f"filename_{i}")
59
+
60
+ if start <= end:
61
+ output_files_with_ranges.append((output_filename, (start, end)))
62
+ else:
63
+ st.warning(f"End page must be greater than or equal to start page for split {i + 1}.")
64
+
65
+ if st.button("Split PDF"):
66
+ split_pdf(input_pdf_path, output_files_with_ranges)