-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdftool.py
More file actions
841 lines (719 loc) · 29 KB
/
Copy pathpdftool.py
File metadata and controls
841 lines (719 loc) · 29 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
import io
import json
import base64
from pathlib import Path
from typing import Dict, List, Union, Tuple, Optional
import streamlit as st
import pandas as pd
from pypdf import PdfReader, PdfWriter
from pypdf.errors import PdfReadError, DependencyError
# Optional YAML for presets
try:
import yaml # type: ignore
_HAVE_YAML = True
except Exception:
_HAVE_YAML = False
# Optional PyMuPDF for fast page previews (thumbnails) + robust normalization
try:
import fitz # PyMuPDF
_HAVE_FITZ = True
except Exception:
_HAVE_FITZ = False
ICON_URL = "https://raw.githubusercontent.com/baliant/pdftool/main/icon/koru_logo.png"
st.set_page_config(
page_title="PDF Select, Review & Merge",
page_icon=ICON_URL,
layout="wide",
)
CRYPTO_HINT = (
"Decryption requires a crypto backend. Install one of:\n"
"`pip install cryptography` (recommended)\n"
"or `pip install pycryptodome`"
)
# ---------- Session state ----------
if "merged_pdf_bytes" not in st.session_state:
st.session_state.merged_pdf_bytes = None
if "merged_pdf_name" not in st.session_state:
st.session_state.merged_pdf_name = "merged.pdf"
if "merged_pdf_info" not in st.session_state:
st.session_state.merged_pdf_info = ""
# ---------- Helpers ----------
def try_open_reader(data: bytes) -> Optional[PdfReader]:
"""Open a PdfReader safely (no page access), return None on hard failure."""
try:
bio = io.BytesIO(data)
reader = PdfReader(bio, strict=False)
return reader
except (PdfReadError, OSError) as e:
st.warning(f"Cannot open PDF: {e}")
return None
def is_probably_signed_pdf(data: bytes) -> bool:
"""Best-effort detection for signed / certified PDFs."""
if _HAVE_FITZ:
try:
doc = fitz.open(stream=data, filetype="pdf")
try:
if getattr(doc, "has_signatures", False):
return True
finally:
doc.close()
except Exception:
pass
reader = try_open_reader(data)
if not reader:
return False
try:
root = reader.trailer.get("/Root", {})
acro = root.get("/AcroForm")
if acro:
return True
except Exception:
pass
return False
def flatten_pdf_with_fitz(data: bytes, password: str = "") -> bytes:
"""
Create a clean working copy with PyMuPDF.
Intended for merge/print workflows, not signature preservation.
"""
if not _HAVE_FITZ:
raise RuntimeError("PyMuPDF is not available.")
doc = fitz.open(stream=data, filetype="pdf")
try:
needs_pass = False
try:
needs_pass = bool(getattr(doc, "needs_pass", False))
except Exception:
needs_pass = False
if needs_pass:
if not password:
raise ValueError("Password required for secured PDF.")
ok = doc.authenticate(password)
if not ok:
raise ValueError("Invalid password for secured PDF.")
# Create a fresh working copy that is usually easier to merge
return doc.tobytes(garbage=3, deflate=True)
finally:
doc.close()
def normalize_pdf_for_merge(data: bytes, password: str = "") -> bytes:
"""
Return merge-friendly PDF bytes.
For signed/encrypted/problematic PDFs, try to create a clean working copy first.
"""
reader = try_open_reader(data)
if not reader:
raise ValueError("Cannot open PDF.")
should_normalize = False
if reader.is_encrypted:
should_normalize = True
elif is_probably_signed_pdf(data):
should_normalize = True
if not should_normalize:
return data
if _HAVE_FITZ:
return flatten_pdf_with_fitz(data, password=password)
# Fallback if fitz is unavailable
try:
if reader.is_encrypted:
ok = bool(reader.decrypt(password))
if not ok:
raise ValueError("Invalid password for encrypted PDF.")
tmp_writer = PdfWriter()
for page in reader.pages:
tmp_writer.add_page(page)
out = io.BytesIO()
tmp_writer.write(out)
out.seek(0)
return out.getvalue()
except DependencyError:
raise
except Exception as e:
raise ValueError(f"Could not prepare PDF for merge: {e}")
def try_decrypt_reader(reader: PdfReader, password: str) -> bool:
"""Attempt to decrypt. Returns True if unlocked."""
try:
res = reader.decrypt(password)
if not bool(res):
return False
# Force some real access, not just decrypt return code
_ = len(reader.pages)
if len(reader.pages) > 0:
_ = reader.pages[0]
return True
except DependencyError:
st.error(f"Cannot decrypt: crypto backend missing.\n\n{CRYPTO_HINT}")
return False
except Exception as e:
st.warning(f"Failed to decrypt with the provided password: {e}")
return False
def get_num_pages_safe(reader: PdfReader) -> int:
"""Return page count, guarding against encryption/crypto issues."""
try:
return len(reader.pages)
except DependencyError:
st.error(f"Cannot read pages (crypto backend missing).\n\n{CRYPTO_HINT}")
return 0
except Exception as e:
st.warning(f"Could not read page count: {e}")
return 0
def parse_one_pagespec(token: str, max_pages: int) -> List[int]:
t = token.strip().lower()
if not t:
return []
if t == "all":
return list(range(1, max_pages + 1))
if "-" in t:
if t.count("-") > 1:
raise ValueError(f"Invalid range: {t}")
start, end = t.split("-", 1)
if start == "" and end == "":
raise ValueError(f"Invalid open range: {t}")
if start == "":
e = int(end)
if e < 1:
raise ValueError(f"Invalid end in range: {t}")
e = min(e, max_pages)
return list(range(1, e + 1))
if end == "":
s = int(start)
if s < 1:
raise ValueError(f"Invalid start in range: {t}")
s = min(s, max_pages)
return list(range(s, max_pages + 1))
s = int(start)
e = int(end)
if s < 1 or e < 1 or s > e:
raise ValueError(f"Invalid range: {t}")
s = min(s, max_pages)
e = min(e, max_pages)
return list(range(s, e + 1))
n = int(t)
if n < 1:
raise ValueError(f"Invalid page number: {t}")
n = min(n, max_pages)
return [n]
def parse_pagespec(spec: Union[str, List[str]], max_pages: int) -> List[int]:
if isinstance(spec, str):
parts = [p for p in spec.split(",") if p.strip()]
else:
parts = list(spec)
pages: List[int] = []
for part in parts:
pages.extend(parse_one_pagespec(part, max_pages))
seen = set()
uniq: List[int] = []
for p in pages:
if p not in seen:
uniq.append(p)
seen.add(p)
return uniq
def load_selection_mapping(data: bytes, suffix: str):
suffix = suffix.lower()
text = data.decode("utf-8")
if suffix in (".yaml", ".yml"):
if not _HAVE_YAML:
st.error("PyYAML is not installed on the server environment. Install with: pip install pyyaml")
return {}
return yaml.safe_load(text) or {}
return json.loads(text)
def _unique_key(prefix: str, name_or_path: str, data_bytes: Optional[bytes] = None) -> str:
base = f"{prefix}:{name_or_path}"
if data_bytes is not None:
import hashlib
h = hashlib.md5(data_bytes).hexdigest()[:8]
base += f":{h}"
return base
@st.cache_resource(show_spinner=False)
def _load_doc_for_preview(data: bytes):
if not _HAVE_FITZ:
return None
try:
return fitz.open(stream=data, filetype="pdf")
except Exception:
return None
def render_page_image(data: bytes, page_index0: int, zoom: float = 1.5) -> Optional[bytes]:
"""Render one page to PNG. Returns PNG bytes or None."""
if not _HAVE_FITZ:
return None
doc = _load_doc_for_preview(data)
if doc is None:
return None
if page_index0 < 0 or page_index0 >= doc.page_count:
return None
try:
page = doc.load_page(page_index0)
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat, alpha=False)
return pix.tobytes("png")
except Exception:
return None
def embed_pdf_viewer(data: bytes, height: int = 480):
"""Inline PDF viewer using base64 in an iframe (works for small/medium files)."""
b64 = base64.b64encode(data).decode("ascii")
src = f"data:application/pdf;base64,{b64}#view=FitH"
st.components.v1.html(
f'<iframe src="{src}" width="100%" height="{height}" style="border:none;"></iframe>',
height=height,
scrolling=False,
)
def page_selector(label: str, pages: int, key: str):
"""Safe page picker: slider for ≥2 pages, number_input for 1 page, skip for 0."""
try:
pages = int(pages)
except Exception:
pages = 0
if pages < 1:
st.warning("This PDF appears to have no pages (cannot preview).")
return None
if pages == 1:
st.caption("This PDF has 1 page.")
return st.number_input(label, min_value=1, max_value=1, value=1, step=1, key=key)
return st.slider(label, min_value=1, max_value=pages, value=1, step=1, key=key)
# ---------- UI ----------
st.title("📚 PDF Select, Review & Merge")
st.caption("Handles encrypted PDFs, signed/certified PDFs, page previews, flexible selections, and merging.")
with st.expander("Page selection syntax help"):
st.markdown(
"""
**Syntax (1-based):**
- Single page: `7`
- Range: `3-9`
- Open start: `-5` (pages 1..5)
- Open end: `4-` (pages 4..last)
- Comma list: `1-3,5,10-12`
- `all` for all pages
"""
)
tab_upload, tab_folder, tab_review = st.tabs(["📤 Upload PDFs", "📁 Folder path (local run)", "🧐 Review"])
selections: Dict[str, List[int]] = {}
file_entries: List[Tuple[str, bytes]] = []
passwords: Dict[str, str] = {}
# ----- Upload Tab -----
with tab_upload:
uploaded = st.file_uploader("Select one or more PDFs", type=["pdf"], accept_multiple_files=True)
mapping_file = st.file_uploader(
"Optional selections mapping (YAML or JSON)",
type=["yaml", "yml", "json"],
key="map_upload",
)
uploaded_mapping = {}
if mapping_file is not None:
try:
uploaded_mapping = load_selection_mapping(mapping_file.getvalue(), Path(mapping_file.name).suffix)
except Exception as e:
st.error(f"Failed to load mapping: {e}")
if uploaded:
st.subheader("Files")
for f in uploaded:
data = f.getvalue()
reader = try_open_reader(data)
if not reader:
continue
pw_key = _unique_key("pw", f.name, data)
if reader.is_encrypted:
st.info(f"🔒 {f.name} is encrypted.")
unlocked = False
try:
unlocked = bool(reader.decrypt(""))
except DependencyError:
st.error(CRYPTO_HINT)
except Exception:
unlocked = False
if not unlocked:
pw = st.text_input(f"Password for {f.name}", type="password", key=pw_key)
if pw:
unlocked = try_decrypt_reader(reader, pw)
if unlocked:
passwords[f.name] = pw
if not unlocked:
st.warning("Locked: cannot show page count/preview until decrypted.")
default_spec = uploaded_mapping.get(f.name, "all") if uploaded_mapping else "all"
spec_key = _unique_key("spec", f.name, data)
spec = st.text_input(f"Pages for {f.name}", value=str(default_spec), key=spec_key)
try:
selections[f.name] = parse_pagespec(spec, 999999)
except Exception:
pass
file_entries.append((f.name, data))
continue
pages = get_num_pages_safe(reader)
left, right = st.columns([2, 1])
with left:
st.markdown(f"**{f.name}** — {pages} pages")
if is_probably_signed_pdf(data):
st.info(
f"{f.name} appears to be signed/certified. "
"A working copy may be created for merge; the original file remains unchanged."
)
default_spec = uploaded_mapping.get(f.name, "all") if uploaded_mapping else "all"
spec_key = _unique_key("spec", f.name, data)
spec = st.text_input(f"Pages for {f.name}", value=str(default_spec), key=spec_key)
with st.expander("Review this PDF"):
if not _HAVE_FITZ:
st.info("Install **PyMuPDF** (`pip install pymupdf`) to enable page previews.")
else:
pnum_key = _unique_key("prev", f.name, data)
pnum = page_selector("Preview page", pages, key=pnum_key)
if pnum is not None:
png = render_page_image(data, int(pnum) - 1, zoom=1.5)
if png:
st.image(png, caption=f"{f.name} — Page {pnum}", use_container_width=True)
show_full_key = _unique_key("viewer", f.name, data)
show_full = st.checkbox("Inline full PDF viewer", value=False, key=show_full_key)
if show_full:
embed_pdf_viewer(data, height=500)
with right:
st.caption("Selected pages preview")
try:
pages_list = parse_pagespec(spec, pages)
if not pages_list:
st.warning("No valid pages; this file will be skipped.")
else:
st.caption(f"Selected pages: {len(pages_list)}")
s = ", ".join(map(str, pages_list[:10]))
more = "" if len(pages_list) <= 10 else " …"
st.text(f"{s}{more}")
selections[f.name] = pages_list
file_entries.append((f.name, data))
except Exception as e:
st.error(f"Invalid page spec for {f.name}: {e}")
# ----- Folder Tab -----
with tab_folder:
st.write("Enter a local folder path to scan for PDFs. (This only works when you run Streamlit locally.)")
folder = st.text_input("Folder path", value="")
mapping2 = st.file_uploader(
"Optional selections mapping (YAML or JSON)",
type=["yaml", "yml", "json"],
key="map_folder",
)
folder_mapping = {}
if mapping2 is not None:
try:
folder_mapping = load_selection_mapping(mapping2.getvalue(), Path(mapping2.name).suffix)
except Exception as e:
st.error(f"Failed to load mapping: {e}")
if folder:
p = Path(folder).expanduser()
if not p.exists():
st.error("Folder does not exist.")
else:
pdfs = sorted(p.rglob("*.pdf"))
if not pdfs:
st.warning("No PDFs found in the folder (recursively).")
else:
st.subheader("Files")
for pf in pdfs:
try:
data = pf.read_bytes()
except Exception as e:
st.warning(f"Cannot read {pf}: {e}")
continue
reader = try_open_reader(data)
if not reader:
continue
pw_key = _unique_key("pw", str(pf))
if reader.is_encrypted:
st.info(f"🔒 {pf.name} is encrypted.")
unlocked = False
try:
unlocked = bool(reader.decrypt(""))
except DependencyError:
st.error(CRYPTO_HINT)
except Exception:
unlocked = False
if not unlocked:
pw = st.text_input(f"Password for {pf}", type="password", key=pw_key)
if pw:
unlocked = try_decrypt_reader(reader, pw)
if unlocked:
passwords[str(pf)] = pw
if not unlocked:
st.warning("Locked: cannot show page count/preview until decrypted.")
default_spec = folder_mapping.get(str(pf), folder_mapping.get(pf.name, "all")) if folder_mapping else "all"
spec_key = _unique_key("spec", str(pf))
spec = st.text_input(f"Pages for {pf}", value=str(default_spec), key=spec_key)
try:
selections[str(pf)] = parse_pagespec(spec, 999999)
except Exception:
pass
file_entries.append((str(pf), data))
continue
pages = get_num_pages_safe(reader)
st.markdown(f"**{pf}** — {pages} pages")
if is_probably_signed_pdf(data):
st.info(
f"{pf.name} appears to be signed/certified. "
"A working copy may be created for merge; the original file remains unchanged."
)
default_spec = "all"
if folder_mapping:
if str(pf) in folder_mapping:
default_spec = folder_mapping[str(pf)]
elif pf.name in folder_mapping:
default_spec = folder_mapping[pf.name]
spec_key = _unique_key("spec", str(pf))
spec = st.text_input(f"Pages for {pf}", value=str(default_spec), key=spec_key)
try:
pages_list = parse_pagespec(spec, pages)
if not pages_list:
st.warning("No valid pages selected; this file will be skipped.")
else:
selections[str(pf)] = pages_list
file_entries.append((str(pf), data))
except Exception as e:
st.error(f"Invalid page spec for {pf}: {e}")
# ----- Global Review Tab -----
with tab_review:
st.write("Preview uploaded or scanned PDFs. Use the controls to flip pages and verify content before merging.")
if not file_entries:
st.info("No files loaded yet. Upload or select a folder first.")
else:
for name, data in file_entries:
with st.expander(f"🔍 {Path(name).name}"):
reader = try_open_reader(data)
if not reader:
continue
if reader.is_encrypted:
pw = passwords.get(name, "")
ok = False
try:
ok = bool(reader.decrypt(pw))
except DependencyError:
st.error(CRYPTO_HINT)
except Exception:
ok = False
if not ok:
st.warning("Locked: enter password in the Upload/Folder tab to enable preview.")
continue
pages = get_num_pages_safe(reader)
if not _HAVE_FITZ:
st.info("Install **PyMuPDF** (`pip install pymupdf`) to enable page previews.")
else:
c1, c2 = st.columns([3, 2])
with c1:
slider_key = _unique_key("slider", name, data)
pnum = page_selector(f"Page for {Path(name).name}", pages, key=slider_key)
if pnum is not None:
png = render_page_image(data, int(pnum) - 1, zoom=1.5)
if png:
st.image(png, caption=f"{Path(name).name} — Page {pnum}", use_container_width=True)
with c2:
st.write("Inline viewer")
viewer_key = _unique_key("viewer2", name, data)
show_full = st.checkbox("Show full PDF", value=False, key=viewer_key)
if show_full:
embed_pdf_viewer(data, height=450)
# ----- Tabular page selection UI -----
st.markdown("---")
st.markdown("### Page selections (table view)")
if file_entries:
rows = []
for name, data in file_entries:
reader = try_open_reader(data)
if not reader:
continue
if reader.is_encrypted:
pw = passwords.get(name, "")
ok = False
try:
ok = bool(reader.decrypt(pw))
except DependencyError:
st.error(CRYPTO_HINT)
except Exception:
ok = False
if not ok:
st.warning(f"Locked: cannot compute page count for '{name}'.")
continue
max_pages = get_num_pages_safe(reader)
if name in selections and selections[name]:
spec_str = ",".join(str(p) for p in selections[name])
else:
spec_str = "all"
rows.append(
{
"PDF Name": Path(name).name,
"Key": name,
"Pages to be printed": spec_str,
"Sum pages": max_pages,
}
)
if rows:
df = pd.DataFrame(rows)
edited_df = st.data_editor(
df,
num_rows="fixed",
hide_index=True,
key="selection_table",
column_config={
"Key": None,
"PDF Name": st.column_config.TextColumn(disabled=True),
"Pages to be printed": st.column_config.TextColumn(
help="Use syntax: 1,3-5,all,-3,4-",
),
"Sum pages": st.column_config.NumberColumn(disabled=True),
},
)
if st.button("Apply table selections"):
new_selections: Dict[str, List[int]] = {}
had_error = False
for _, row in edited_df.iterrows():
key = row["Key"]
maxp = int(row["Sum pages"])
spec = str(row["Pages to be printed"])
try:
pages_list = parse_pagespec(spec, maxp)
if not pages_list:
st.warning(
f"No valid pages for '{row['PDF Name']}'. "
"This file will be skipped unless you adjust the spec."
)
new_selections[key] = pages_list
except Exception as e:
st.error(f"Invalid page spec for {row['PDF Name']}: {e}")
had_error = True
break
if not had_error:
selections.clear()
selections.update(new_selections)
st.success("Selections updated from table.")
else:
st.info("No readable PDFs to show in table.")
else:
st.info("No files loaded yet. Upload or select a folder first.")
# ----- Merge -----
st.markdown("---")
st.subheader("Merge")
colA, colB, colC = st.columns([2, 1, 1])
with colA:
out_name = st.text_input("Output file name", value="merged.pdf")
with colB:
add_bookmarks = st.checkbox("Add bookmarks per source file", value=True)
with colC:
keep_file_order = st.selectbox(
"File order",
["Upload/scan order (default)", "Alphabetical by name"],
index=0,
)
if file_entries and selections:
merge_entries = file_entries
if keep_file_order == "Alphabetical by name":
merge_entries = sorted(file_entries, key=lambda t: Path(t[0]).name.lower())
if st.button("Merge PDFs"):
writer = PdfWriter()
merged_pages = 0
merged_files = 0
skipped_files = 0
for name, data in merge_entries:
password = passwords.get(name, "")
try:
merge_data = normalize_pdf_for_merge(data, password=password)
except DependencyError:
st.error(
f"Cannot process '{Path(name).name}' because crypto backend is missing.\n\n{CRYPTO_HINT}"
)
skipped_files += 1
continue
except Exception as e:
st.warning(f"Skipping '{Path(name).name}' — cannot prepare for merge: {e}")
skipped_files += 1
continue
reader = try_open_reader(merge_data)
if not reader:
st.warning(f"Skipping '{Path(name).name}' — cannot reopen prepared PDF.")
skipped_files += 1
continue
if reader.is_encrypted:
ok = False
try:
ok = bool(reader.decrypt(password))
except DependencyError:
st.error(CRYPTO_HINT)
except Exception:
ok = False
if not ok:
st.warning(f"Skipping encrypted file '{Path(name).name}' (no/invalid password).")
skipped_files += 1
continue
maxp = get_num_pages_safe(reader)
if maxp < 1:
st.warning(f"Skipping '{Path(name).name}' — no readable pages.")
skipped_files += 1
continue
wanted = selections.get(name, list(range(1, maxp + 1)))
wanted = [p for p in wanted if 1 <= p <= maxp]
if not wanted:
st.warning(f"Skipping '{Path(name).name}' — no valid selected pages.")
skipped_files += 1
continue
if add_bookmarks:
try:
start_idx = len(writer.pages)
if hasattr(writer, "add_outline_item"):
writer.add_outline_item(Path(name).name, start_idx)
elif hasattr(writer, "add_bookmark"):
writer.add_bookmark(Path(name).name, start_idx)
except Exception:
pass
file_added_pages = 0
for p1 in wanted:
idx0 = p1 - 1
try:
writer.add_page(reader.pages[idx0])
merged_pages += 1
file_added_pages += 1
except Exception as e:
st.warning(f"Skipping page {p1} from '{Path(name).name}': {e}")
if file_added_pages > 0:
merged_files += 1
else:
st.warning(f"No pages could be merged from '{Path(name).name}'.")
if merged_pages == 0:
st.session_state.merged_pdf_bytes = None
st.session_state.merged_pdf_name = out_name
st.session_state.merged_pdf_info = ""
st.error("No pages could be merged.")
else:
bio = io.BytesIO()
writer.write(bio)
bio.seek(0)
st.session_state.merged_pdf_bytes = bio.getvalue()
st.session_state.merged_pdf_name = out_name
st.session_state.merged_pdf_info = (
f"Merged {merged_pages} page(s) from {merged_files} file(s). "
f"Skipped files: {skipped_files}."
)
if st.session_state.merged_pdf_bytes:
st.success(st.session_state.merged_pdf_info)
st.download_button(
"Download merged PDF",
data=st.session_state.merged_pdf_bytes,
file_name=st.session_state.merged_pdf_name,
mime="application/pdf",
key="download_merged_pdf",
)
else:
st.info("Add files and valid page selections to enable merging.")
# ----- Export selections -----
if file_entries and selections:
mapping_out = {name: ",".join(map(str, pages)) for name, pages in selections.items()}
col1, col2 = st.columns(2)
with col1:
if _HAVE_YAML:
yaml_bytes = yaml.safe_dump(mapping_out, allow_unicode=True).encode("utf-8")
st.download_button(
"Download selections.yaml",
data=yaml_bytes,
file_name="selections.yaml",
mime="text/yaml",
key="download_yaml_mapping",
)
else:
st.caption("Install **pyyaml** to export YAML mapping.")
with col2:
json_bytes = json.dumps(mapping_out, ensure_ascii=False, indent=2).encode("utf-8")
st.download_button(
"Download selections.json",
data=json_bytes,
file_name="selections.json",
mime="application/json",
key="download_json_mapping",
)