-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDFedit.py
More file actions
3881 lines (3252 loc) · 151 KB
/
PDFedit.py
File metadata and controls
3881 lines (3252 loc) · 151 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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
PDF Editor Pro v4.0 - Professional PDF Editing Suite
A comprehensive Adobe Acrobat Pro alternative with modern UI
NEW IN v4.0:
- Undo/Redo: Ctrl+Z to undo, Ctrl+Y to redo (up to 30 steps)
- Auto OCR: Documents without searchable text are automatically OCR'd in background
- Background processing: OCR runs without locking the UI, with progress bar
- LIVE Text Editing:
- Double-click any text to instantly edit it
- Or use Edit Text tool and single-click
- Enter to apply, Escape to cancel
- Interactive Image Placement:
- Drag to move image anywhere on the page
- Drag corners to resize (maintains aspect ratio)
- Enter to place, Escape to cancel
- Cancel OCR: Stop background OCR processing anytime
- Professional dark theme UI with ribbon toolbar
Features:
- Multi-tab document interface
- Search within documents
- Bookmarks/Outline navigation
- Comments & Sticky Notes
- Stamps library
- Watermarks, Headers & Footers
- Bates numbering
- Export to Word/Images
- Form filling
- Merge, Split, Compress
- Password protection
Auto-installs all dependencies on first run.
"""
import sys
import subprocess
import os
import platform
import urllib.request
import shutil
import tempfile
import json
from pathlib import Path
from datetime import datetime
# ============================================================================
# AUTO-INSTALLER
# ============================================================================
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
TESSERACT_DIR = os.path.join(SCRIPT_DIR, "tesseract_ocr")
CONFIG_DIR = os.path.join(SCRIPT_DIR, "pdf_editor_config")
TESSERACT_VERSION = "5.5.0"
TESSERACT_DATE = "20241111"
TESSERACT_URL = f"https://github.com/tesseract-ocr/tesseract/releases/download/{TESSERACT_VERSION}/tesseract-ocr-w64-setup-{TESSERACT_VERSION}.{TESSERACT_DATE}.exe"
def get_tesseract_path():
if platform.system() == "Windows":
for path in [
os.path.join(TESSERACT_DIR, "tesseract.exe"),
r"C:\Program Files\Tesseract-OCR\tesseract.exe",
r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe",
]:
if os.path.exists(path):
return path
return None
def download_file(url, dest_path, desc="Downloading"):
print(f" {desc}...")
try:
opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
urllib.request.install_opener(opener)
def hook(b, bs, ts):
if ts > 0:
pct = min(100, b * bs * 100 // ts)
print(f"\r [{'█' * (pct//3)}{'░' * (33-pct//3)}] {pct}%", end="", flush=True)
urllib.request.urlretrieve(url, dest_path, hook)
print()
return True
except Exception as e:
print(f"\n Error: {e}")
return False
def install_tesseract_windows():
print("\n Installing Tesseract OCR...")
os.makedirs(TESSERACT_DIR, exist_ok=True)
temp_dir = tempfile.mkdtemp()
installer = os.path.join(temp_dir, "setup.exe")
try:
if download_file(TESSERACT_URL, installer, "Downloading Tesseract OCR (~70MB)"):
print(" Running installer...")
subprocess.run([installer, "/S", f"/D={TESSERACT_DIR}"], capture_output=True, timeout=300)
exe = os.path.join(TESSERACT_DIR, "tesseract.exe")
if os.path.exists(exe):
print(" ✓ Tesseract installed")
shutil.rmtree(temp_dir, ignore_errors=True)
return exe
except:
pass
shutil.rmtree(temp_dir, ignore_errors=True)
return None
def pip_install(pkg):
for method in [
[sys.executable, "-m", "pip", "install", pkg, "-q"],
[sys.executable, "-m", "pip", "install", pkg, "--break-system-packages", "-q"],
[sys.executable, "-m", "pip", "install", pkg, "--user", "-q"],
]:
try:
if subprocess.run(method, capture_output=True, timeout=120).returncode == 0:
return True
except:
pass
return False
def _try_import(name):
try:
__import__(name)
return True
except:
return False
def check_and_install_dependencies():
required = {'PIL': 'Pillow', 'fitz': 'PyMuPDF'}
optional = {'pytesseract': 'pytesseract', 'docx': 'python-docx'}
missing_req = [p for i, p in required.items() if not _try_import(i)]
missing_opt = [p for i, p in optional.items() if not _try_import(i)]
tesseract_needed = get_tesseract_path() is None
if missing_req or missing_opt or tesseract_needed:
print("\n╔══════════════════════════════════════════════════════════╗")
print("║ PDF Editor Pro v4.0 - First Run Setup ║")
print("╚══════════════════════════════════════════════════════════╝\n")
for pkg in missing_req + missing_opt:
print(f" Installing {pkg}...", end=" ", flush=True)
print("✓" if pip_install(pkg) else "⚠")
if tesseract_needed and platform.system() == "Windows":
install_tesseract_windows()
print("\n Setup complete! Starting PDF Editor Pro...\n")
for i, p in required.items():
if not _try_import(i):
print(f"ERROR: {p} required. Run: pip install {p}")
sys.exit(1)
if (path := get_tesseract_path()):
os.environ["TESSERACT_CMD"] = path
check_and_install_dependencies()
# ============================================================================
# IMPORTS
# ============================================================================
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, colorchooser
from PIL import Image, ImageTk, ImageDraw
import fitz
import io
import threading
import math
from dataclasses import dataclass
from typing import Optional, List, Tuple, Dict, Callable, Any
from enum import Enum, auto
from collections import deque
try:
from docx import Document as DocxDocument
HAS_DOCX = True
except ImportError:
HAS_DOCX = False
# ============================================================================
# THEME - Professional Dark UI
# ============================================================================
class Theme:
# Backgrounds - Layered depth
BG_DARK = "#0d0d0d"
BG_PRIMARY = "#161616"
BG_SECONDARY = "#1e1e1e"
BG_TERTIARY = "#262626"
BG_ELEVATED = "#2d2d2d"
BG_HOVER = "#363636"
BG_ACTIVE = "#404040"
BG_INPUT = "#1a1a1a"
BG_CANVAS = "#525252"
# Foregrounds
FG_PRIMARY = "#f5f5f5"
FG_SECONDARY = "#a0a0a0"
FG_MUTED = "#6b6b6b"
FG_DISABLED = "#4a4a4a"
# Accents
ACCENT = "#2563eb"
ACCENT_LIGHT = "#3b82f6"
ACCENT_DARK = "#1d4ed8"
ACCENT_MUTED = "#1e3a5f"
# Status colors
SUCCESS = "#10b981"
WARNING = "#f59e0b"
DANGER = "#ef4444"
INFO = "#06b6d4"
# Borders
BORDER_DARK = "#1a1a1a"
BORDER_LIGHT = "#333333"
BORDER_FOCUS = "#2563eb"
# Special
SELECTION = "#2563eb"
HIGHLIGHT = "#fbbf24"
SHADOW = "#000000"
# Typography
FONT_FAMILY = "Segoe UI"
FONT_MONO = "Consolas"
FONT_SIZE_XS = 9
FONT_SIZE_SM = 10
FONT_SIZE_MD = 11
FONT_SIZE_LG = 12
FONT_SIZE_XL = 14
FONT_SIZE_XXL = 18
# Spacing
PAD_XS = 2
PAD_SM = 4
PAD_MD = 8
PAD_LG = 12
PAD_XL = 16
PAD_XXL = 24
# Sizing
TOOLBAR_HEIGHT = 90
SIDEBAR_WIDTH = 200
STATUSBAR_HEIGHT = 28
TAB_HEIGHT = 36
BUTTON_HEIGHT = 32
ICON_SIZE = 20
# Predefined stamps
BUILTIN_STAMPS = [
{"name": "Approved", "text": "APPROVED", "fg": "#ffffff", "bg": "#10b981"},
{"name": "Rejected", "text": "REJECTED", "fg": "#ffffff", "bg": "#ef4444"},
{"name": "Draft", "text": "DRAFT", "fg": "#000000", "bg": "#fbbf24"},
{"name": "Final", "text": "FINAL", "fg": "#ffffff", "bg": "#2563eb"},
{"name": "Confidential", "text": "CONFIDENTIAL", "fg": "#ffffff", "bg": "#dc2626"},
{"name": "For Review", "text": "FOR REVIEW", "fg": "#000000", "bg": "#fb923c"},
{"name": "Void", "text": "VOID", "fg": "#ffffff", "bg": "#6b7280"},
{"name": "Copy", "text": "COPY", "fg": "#000000", "bg": "#a3e635"},
]
# ============================================================================
# CONFIGURATION
# ============================================================================
class Config:
MAX_RECENT_FILES = 15
MAX_UNDO_STEPS = 100
DEFAULT_ZOOM = 1.0
MIN_ZOOM = 0.1
MAX_ZOOM = 10.0
@staticmethod
def get_config_path():
os.makedirs(CONFIG_DIR, exist_ok=True)
return os.path.join(CONFIG_DIR, "config.json")
@staticmethod
def load():
try:
with open(Config.get_config_path(), 'r') as f:
return json.load(f)
except:
return {"recent_files": [], "window_geometry": "1500x900"}
@staticmethod
def save(data):
try:
with open(Config.get_config_path(), 'w') as f:
json.dump(data, f, indent=2)
except:
pass
# ============================================================================
# ENUMS & DATA CLASSES
# ============================================================================
class ToolMode(Enum):
SELECT = auto()
PAN = auto()
TEXT = auto()
TEXT_EDIT = auto() # Edit existing text
STICKY_NOTE = auto()
HIGHLIGHT = auto()
UNDERLINE = auto()
STRIKETHROUGH = auto()
DRAW = auto()
ERASER = auto()
RECTANGLE = auto()
CIRCLE = auto()
LINE = auto()
ARROW = auto()
IMAGE = auto()
STAMP = auto()
REDACT = auto()
CROP = auto()
LINK = auto()
@dataclass
class TextBlock:
"""Represents an editable text block in the PDF"""
page: int
rect: Tuple[float, float, float, float]
text: str
font_size: float
font_name: str
color: Tuple[float, float, float]
@dataclass
class SearchResult:
page: int
rect: Tuple[float, float, float, float]
text: str
@dataclass
class Comment:
id: str
page: int
x: float
y: float
content: str
author: str = "User"
date: str = ""
color: str = "#fbbf24"
# ============================================================================
# STYLED WIDGETS
# ============================================================================
class ModernButton(tk.Canvas):
"""Modern flat button with hover effects"""
def __init__(self, parent, text="", icon="", command=None, width=None,
style="default", tooltip="", **kw):
self.btn_width = width or (36 if not text else max(80, len(text) * 8 + 24))
self.btn_height = 32
super().__init__(parent, width=self.btn_width, height=self.btn_height,
bg=Theme.BG_SECONDARY, highlightthickness=0, **kw)
self.text = text
self.icon = icon
self.command = command
self.style = style
self.tooltip_text = tooltip
self.state = "normal" # normal, hover, pressed, disabled
self._tip_window = None
self._draw()
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<Button-1>", self._on_press)
self.bind("<ButtonRelease-1>", self._on_release)
def _get_colors(self):
if self.state == "disabled":
return Theme.BG_TERTIARY, Theme.FG_DISABLED
if self.style == "primary":
if self.state == "pressed":
return Theme.ACCENT_DARK, Theme.FG_PRIMARY
elif self.state == "hover":
return Theme.ACCENT_LIGHT, Theme.FG_PRIMARY
return Theme.ACCENT, Theme.FG_PRIMARY
elif self.style == "danger":
if self.state == "pressed":
return "#b91c1c", Theme.FG_PRIMARY
elif self.state == "hover":
return "#f87171", Theme.FG_PRIMARY
return Theme.DANGER, Theme.FG_PRIMARY
else: # default
if self.state == "pressed":
return Theme.BG_ACTIVE, Theme.FG_PRIMARY
elif self.state == "hover":
return Theme.BG_HOVER, Theme.FG_PRIMARY
return Theme.BG_TERTIARY, Theme.FG_SECONDARY
def _draw(self):
self.delete("all")
bg, fg = self._get_colors()
# Background with rounded corners effect
self.create_rectangle(1, 1, self.btn_width-1, self.btn_height-1,
fill=bg, outline=Theme.BORDER_LIGHT if self.style == "default" else bg)
# Content
if self.icon and self.text:
self.create_text(18, self.btn_height//2, text=self.icon, fill=fg,
font=(Theme.FONT_FAMILY, 12))
self.create_text(36, self.btn_height//2, text=self.text, fill=fg,
font=(Theme.FONT_FAMILY, Theme.FONT_SIZE_SM), anchor="w")
elif self.icon:
self.create_text(self.btn_width//2, self.btn_height//2, text=self.icon,
fill=fg, font=(Theme.FONT_FAMILY, 14))
else:
self.create_text(self.btn_width//2, self.btn_height//2, text=self.text,
fill=fg, font=(Theme.FONT_FAMILY, Theme.FONT_SIZE_SM))
def _on_enter(self, e):
if self.state != "disabled":
self.state = "hover"
self._draw()
self._show_tooltip()
def _on_leave(self, e):
if self.state != "disabled":
self.state = "normal"
self._draw()
self._hide_tooltip()
def _on_press(self, e):
if self.state != "disabled":
self.state = "pressed"
self._draw()
def _on_release(self, e):
if self.state != "disabled":
self.state = "hover"
self._draw()
if self.command and 0 <= e.x <= self.btn_width and 0 <= e.y <= self.btn_height:
self.command()
def _show_tooltip(self):
if not self.tooltip_text:
return
x = self.winfo_rootx() + self.btn_width // 2
y = self.winfo_rooty() + self.btn_height + 5
self._tip_window = tk.Toplevel(self)
self._tip_window.wm_overrideredirect(True)
self._tip_window.wm_geometry(f"+{x}+{y}")
frame = tk.Frame(self._tip_window, bg=Theme.BG_ELEVATED, padx=8, pady=4)
frame.pack()
tk.Label(frame, text=self.tooltip_text, bg=Theme.BG_ELEVATED, fg=Theme.FG_PRIMARY,
font=(Theme.FONT_FAMILY, Theme.FONT_SIZE_XS)).pack()
def _hide_tooltip(self):
if self._tip_window:
self._tip_window.destroy()
self._tip_window = None
def set_state(self, state):
self.state = state
self._draw()
class ToolbarButton(tk.Canvas):
"""Toolbar button with icon and optional label"""
def __init__(self, parent, icon="", label="", command=None, toggle=False,
tooltip="", size="normal", **kw):
self.size = 48 if size == "normal" else 36
self.show_label = size == "normal" and label
height = 56 if self.show_label else self.size
super().__init__(parent, width=self.size, height=height,
bg=Theme.BG_SECONDARY, highlightthickness=0, **kw)
self.icon = icon
self.label = label
self.command = command
self.toggle = toggle
self.tooltip_text = tooltip
self.active = False
self.hover = False
self._tip = None
self._draw()
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<Button-1>", self._on_click)
def _draw(self):
self.delete("all")
# Background
if self.active:
self.create_rectangle(2, 2, self.size-2, self.size-2,
fill=Theme.ACCENT_MUTED, outline=Theme.ACCENT)
elif self.hover:
self.create_rectangle(2, 2, self.size-2, self.size-2,
fill=Theme.BG_HOVER, outline="")
# Icon
icon_y = 20 if self.show_label else self.size // 2
fg = Theme.ACCENT_LIGHT if self.active else (Theme.FG_PRIMARY if self.hover else Theme.FG_SECONDARY)
self.create_text(self.size//2, icon_y, text=self.icon, fill=fg,
font=(Theme.FONT_FAMILY, 16))
# Label
if self.show_label:
self.create_text(self.size//2, 42, text=self.label, fill=Theme.FG_MUTED,
font=(Theme.FONT_FAMILY, Theme.FONT_SIZE_XS))
def _on_enter(self, e):
self.hover = True
self._draw()
if self.tooltip_text and not self.show_label:
self._tip = tk.Toplevel(self)
self._tip.wm_overrideredirect(True)
self._tip.wm_geometry(f"+{self.winfo_rootx()}+{self.winfo_rooty()+self.size+5}")
frame = tk.Frame(self._tip, bg=Theme.BG_ELEVATED, padx=6, pady=3)
frame.pack()
tk.Label(frame, text=self.tooltip_text, bg=Theme.BG_ELEVATED,
fg=Theme.FG_PRIMARY, font=(Theme.FONT_FAMILY, Theme.FONT_SIZE_XS)).pack()
def _on_leave(self, e):
self.hover = False
self._draw()
if self._tip:
self._tip.destroy()
self._tip = None
def _on_click(self, e):
if self.toggle:
self.active = not self.active
self._draw()
if self.command:
self.command()
def set_active(self, active):
self.active = active
self._draw()
class ToolbarSeparator(tk.Frame):
def __init__(self, parent, **kw):
super().__init__(parent, width=1, height=40, bg=Theme.BORDER_LIGHT, **kw)
class ToolbarGroup(tk.Frame):
"""Group of toolbar buttons with label"""
def __init__(self, parent, label="", **kw):
super().__init__(parent, bg=Theme.BG_SECONDARY, **kw)
self.buttons_frame = tk.Frame(self, bg=Theme.BG_SECONDARY)
self.buttons_frame.pack(pady=(4, 2))
if label:
tk.Label(self, text=label, bg=Theme.BG_SECONDARY, fg=Theme.FG_MUTED,
font=(Theme.FONT_FAMILY, Theme.FONT_SIZE_XS)).pack()
def add_button(self, **kw):
btn = ToolbarButton(self.buttons_frame, **kw)
btn.pack(side=tk.LEFT, padx=1)
return btn
class ModernEntry(tk.Entry):
"""Styled entry widget"""
def __init__(self, parent, placeholder="", **kw):
super().__init__(parent, bg=Theme.BG_INPUT, fg=Theme.FG_PRIMARY,
insertbackground=Theme.FG_PRIMARY, relief=tk.FLAT,
font=(Theme.FONT_FAMILY, Theme.FONT_SIZE_SM),
highlightthickness=1, highlightcolor=Theme.BORDER_FOCUS,
highlightbackground=Theme.BORDER_LIGHT, **kw)
self.placeholder = placeholder
self._has_placeholder = False
if placeholder:
self._show_placeholder()
self.bind("<FocusIn>", self._on_focus_in)
self.bind("<FocusOut>", self._on_focus_out)
def _show_placeholder(self):
if not self.get():
self._has_placeholder = True
self.insert(0, self.placeholder)
self.configure(fg=Theme.FG_MUTED)
def _on_focus_in(self, e):
if self._has_placeholder:
self.delete(0, tk.END)
self.configure(fg=Theme.FG_PRIMARY)
self._has_placeholder = False
def _on_focus_out(self, e):
if not self.get():
self._show_placeholder()
def get_value(self):
if self._has_placeholder:
return ""
return self.get()
class TabButton(tk.Canvas):
"""Document tab button"""
def __init__(self, parent, title="", doc_id="", on_select=None, on_close=None, **kw):
super().__init__(parent, width=180, height=Theme.TAB_HEIGHT,
bg=Theme.BG_PRIMARY, highlightthickness=0, **kw)
self.title = title
self.doc_id = doc_id
self.on_select = on_select
self.on_close = on_close
self.active = False
self.hover = False
self.close_hover = False
self._draw()
self.bind("<Enter>", self._on_enter)
self.bind("<Leave>", self._on_leave)
self.bind("<Button-1>", self._on_click)
self.bind("<Motion>", self._on_motion)
def _draw(self):
self.delete("all")
# Background
bg = Theme.BG_TERTIARY if self.active else (Theme.BG_SECONDARY if self.hover else Theme.BG_PRIMARY)
self.create_rectangle(0, 0, 180, Theme.TAB_HEIGHT, fill=bg, outline="")
# Active indicator
if self.active:
self.create_rectangle(0, Theme.TAB_HEIGHT - 2, 180, Theme.TAB_HEIGHT,
fill=Theme.ACCENT, outline="")
# Icon
self.create_text(16, Theme.TAB_HEIGHT//2, text="📄", font=(Theme.FONT_FAMILY, 10))
# Title
display_title = self.title[:18] + "..." if len(self.title) > 18 else self.title
self.create_text(30, Theme.TAB_HEIGHT//2, text=display_title,
fill=Theme.FG_PRIMARY if self.active else Theme.FG_SECONDARY,
font=(Theme.FONT_FAMILY, Theme.FONT_SIZE_SM), anchor="w")
# Close button
close_bg = Theme.BG_HOVER if self.close_hover else ""
if close_bg:
self.create_oval(152, 8, 172, 28, fill=close_bg, outline="")
self.create_text(162, Theme.TAB_HEIGHT//2, text="×",
fill=Theme.FG_PRIMARY if self.close_hover else Theme.FG_MUTED,
font=(Theme.FONT_FAMILY, 14))
def _on_enter(self, e):
self.hover = True
self._draw()
def _on_leave(self, e):
self.hover = False
self.close_hover = False
self._draw()
def _on_motion(self, e):
in_close = 152 <= e.x <= 172 and 8 <= e.y <= 28
if in_close != self.close_hover:
self.close_hover = in_close
self._draw()
def _on_click(self, e):
if 152 <= e.x <= 172 and 8 <= e.y <= 28:
if self.on_close:
self.on_close(self.doc_id)
else:
if self.on_select:
self.on_select(self.doc_id)
def set_active(self, active):
self.active = active
self._draw()
def set_title(self, title):
self.title = title
self._draw()
class SidebarTab(tk.Canvas):
"""Sidebar navigation tab"""
def __init__(self, parent, icon="", label="", command=None, **kw):
super().__init__(parent, width=Theme.SIDEBAR_WIDTH, height=40,
bg=Theme.BG_SECONDARY, highlightthickness=0, **kw)
self.icon = icon
self.label = label
self.command = command
self.active = False
self.hover = False
self._draw()
self.bind("<Enter>", lambda e: self._set_hover(True))
self.bind("<Leave>", lambda e: self._set_hover(False))
self.bind("<Button-1>", self._on_click)
def _draw(self):
self.delete("all")
if self.active:
self.create_rectangle(0, 0, 3, 40, fill=Theme.ACCENT, outline="")
self.create_rectangle(3, 0, Theme.SIDEBAR_WIDTH, 40, fill=Theme.BG_TERTIARY, outline="")
fg = Theme.FG_PRIMARY
elif self.hover:
self.create_rectangle(0, 0, Theme.SIDEBAR_WIDTH, 40, fill=Theme.BG_HOVER, outline="")
fg = Theme.FG_PRIMARY
else:
fg = Theme.FG_SECONDARY
self.create_text(24, 20, text=self.icon, fill=fg, font=(Theme.FONT_FAMILY, 14))
self.create_text(48, 20, text=self.label, fill=fg,
font=(Theme.FONT_FAMILY, Theme.FONT_SIZE_SM), anchor="w")
def _set_hover(self, h):
self.hover = h
self._draw()
def _on_click(self, e):
if self.command:
self.command()
def set_active(self, active):
self.active = active
self._draw()
# ============================================================================
# PDF DOCUMENT CLASS
# ============================================================================
class PDFDocument:
def __init__(self):
self.doc = None
self.filepath = None
self.is_modified = False
self.comments = []
self._comment_counter = 0
# Undo/Redo stacks - store document bytes
self._undo_stack = []
self._redo_stack = []
self._max_undo = 30 # Limit to prevent excessive memory usage
def _save_undo_state(self):
"""Save current document state for undo"""
if not self.doc:
return
try:
# Save document to bytes
state = self.doc.tobytes(garbage=0, deflate=False)
self._undo_stack.append({
'doc_bytes': state,
'comments': [Comment(c.id, c.page, c.x, c.y, c.content, c.author, c.date, c.color)
for c in self.comments],
'page': None # Will be set by caller if needed
})
# Limit stack size
while len(self._undo_stack) > self._max_undo:
self._undo_stack.pop(0)
# Clear redo stack on new change
self._redo_stack.clear()
except Exception as e:
print(f"Save undo state error: {e}")
def undo(self):
"""Restore previous document state"""
if not self._undo_stack:
return False
try:
# Save current state for redo
current_state = self.doc.tobytes(garbage=0, deflate=False)
self._redo_stack.append({
'doc_bytes': current_state,
'comments': [Comment(c.id, c.page, c.x, c.y, c.content, c.author, c.date, c.color)
for c in self.comments]
})
# Restore previous state
state = self._undo_stack.pop()
self.doc.close()
self.doc = fitz.open(stream=state['doc_bytes'], filetype="pdf")
self.comments = state['comments']
self.is_modified = True
return True
except Exception as e:
print(f"Undo error: {e}")
return False
def redo(self):
"""Restore next document state (after undo)"""
if not self._redo_stack:
return False
try:
# Save current state for undo
current_state = self.doc.tobytes(garbage=0, deflate=False)
self._undo_stack.append({
'doc_bytes': current_state,
'comments': [Comment(c.id, c.page, c.x, c.y, c.content, c.author, c.date, c.color)
for c in self.comments]
})
# Restore redo state
state = self._redo_stack.pop()
self.doc.close()
self.doc = fitz.open(stream=state['doc_bytes'], filetype="pdf")
self.comments = state['comments']
self.is_modified = True
return True
except Exception as e:
print(f"Redo error: {e}")
return False
def can_undo(self):
return len(self._undo_stack) > 0
def can_redo(self):
return len(self._redo_stack) > 0
def clear_undo_history(self):
"""Clear undo/redo stacks (e.g., after save)"""
self._undo_stack.clear()
self._redo_stack.clear()
def open(self, filepath):
try:
self.doc = fitz.open(filepath)
self.filepath = filepath
self.is_modified = False
self.comments = []
self._load_comments()
return True
except Exception as e:
print(f"Open error: {e}")
return False
def create_new(self, width=612, height=792):
self.doc = fitz.open()
self.doc.new_page(width=width, height=height)
self.filepath = None
self.is_modified = True
def save(self, filepath=None):
if not self.doc:
return False
path = filepath or self.filepath
if not path:
return False
try:
self._save_comments()
if path == self.filepath:
self.doc.saveIncr()
else:
self.doc.save(path, garbage=4, deflate=True)
self.filepath = path
self.is_modified = False
return True
except:
return False
def close(self):
if self.doc:
self.doc.close()
self.__init__()
@property
def page_count(self):
return len(self.doc) if self.doc else 0
@property
def filename(self):
return os.path.basename(self.filepath) if self.filepath else "Untitled"
def get_page(self, num):
if self.doc and 0 <= num < len(self.doc):
return self.doc[num]
return None
def render_page(self, page_num, zoom=1.0):
page = self.get_page(page_num)
if not page:
return None
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat, alpha=False)
return Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
def get_page_size(self, page_num):
page = self.get_page(page_num)
return (page.rect.width, page.rect.height) if page else (612, 792)
def get_text(self, page_num):
page = self.get_page(page_num)
return page.get_text() if page else ""
def search_text(self, query, case_sensitive=False):
results = []
if not self.doc or not query:
return results
for i in range(len(self.doc)):
for rect in self.doc[i].search_for(query):
results.append(SearchResult(i, tuple(rect), query))
return results
def get_text_blocks(self, page_num):
"""Get all text blocks on a page for editing"""
page = self.get_page(page_num)
if not page:
return []
blocks = []
text_dict = page.get_text("dict", flags=fitz.TEXT_PRESERVE_WHITESPACE)
for block in text_dict.get("blocks", []):
if block.get("type") == 0: # Text block
for line in block.get("lines", []):
for span in line.get("spans", []):
text = span.get("text", "").strip()
if text:
bbox = span.get("bbox", (0, 0, 0, 0))
blocks.append(TextBlock(
page=page_num,
rect=tuple(bbox),
text=text,
font_size=span.get("size", 12),
font_name=span.get("font", "helv"),
color=self._extract_color(span.get("color", 0))
))
return blocks
def _extract_color(self, color_int):
"""Convert integer color to RGB tuple"""
if isinstance(color_int, (list, tuple)):
return tuple(color_int)
# Convert integer to RGB
b = (color_int >> 16) & 0xFF
g = (color_int >> 8) & 0xFF
r = color_int & 0xFF
return (r/255, g/255, b/255)
def get_text_at_point(self, page_num, x, y):
"""Find text block at a specific point"""
blocks = self.get_text_blocks(page_num)
for block in blocks:
r = block.rect
if r[0] <= x <= r[2] and r[1] <= y <= r[3]:
return block
return None
def edit_text(self, page_num, old_rect, old_text, new_text, font_size=None, color=None):
"""Edit text in place by redacting old and inserting new"""
page = self.get_page(page_num)
if not page:
return False
try:
self._save_undo_state()
# Create redaction annotation for old text area
rect = fitz.Rect(old_rect)
# Expand rect slightly to ensure full coverage
rect = rect + (-1, -1, 1, 1)
# Add redaction with white fill (to match page background)
page.add_redact_annot(rect, fill=(1, 1, 1))
page.apply_redactions()
# Insert new text at the same position
if new_text.strip():
fs = font_size or 12
text_color = color or (0, 0, 0)
# Calculate position (baseline)
x = old_rect[0]
y = old_rect[3] - 2 # Slightly above bottom
page.insert_text(
(x, y),
new_text,
fontsize=fs,
fontname="helv",
color=text_color
)
self.is_modified = True
return True
except Exception as e:
print(f"Edit text error: {e}")
return False
def delete_text(self, page_num, rect):
"""Delete text in a region by redacting with white"""
page = self.get_page(page_num)
if not page:
return False
try:
self._save_undo_state()
r = fitz.Rect(rect) + (-1, -1, 1, 1)
page.add_redact_annot(r, fill=(1, 1, 1))
page.apply_redactions()
self.is_modified = True
return True