-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpdf_editor.py
More file actions
992 lines (818 loc) · 40.2 KB
/
Copy pathpdf_editor.py
File metadata and controls
992 lines (818 loc) · 40.2 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
#!/usr/bin/env python3
"""
PDF Editor - Program do manipulacji plikami PDF
"""
import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import fitz
import os
import io
from PIL import Image, ImageTk
try:
from docx import Document
DOCX_AVAILABLE = True
except ImportError:
DOCX_AVAILABLE = False
class ToolTip:
"""Klasa pomocnicza dla tooltipów"""
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tooltip = None
self.widget.bind("<Enter>", self.show)
self.widget.bind("<Leave>", self.hide)
def show(self, event=None):
x = self.widget.winfo_rootx() + 20
y = self.widget.winfo_rooty() + self.widget.winfo_height() + 5
self.tooltip = tk.Toplevel(self.widget)
self.tooltip.wm_overrideredirect(True)
self.tooltip.wm_geometry(f"+{x}+{y}")
label = tk.Label(self.tooltip, text=self.text, justify=tk.LEFT,
background="#ffffe0", relief=tk.SOLID, borderwidth=1,
font=("Arial", 9))
label.pack()
def hide(self, event=None):
if self.tooltip:
self.tooltip.destroy()
self.tooltip = None
class PDFEditorApp:
def __init__(self, root):
self.root = root
self.root.title("Edytor PDF")
self.root.geometry("1200x800")
self.doc = None
self.pages_list = []
self.current_file_path = None
self.preview_image = None
self.selected_page_idx = None
# Historia operacji z pełnym stanem
self.history = []
self.history_index = -1
self.max_history = 30 # Maksymalnie 30 pozycji w historii
# Źródłowe dokumenty - zarządzanie pamięcią
self.source_docs = {} # path -> fitz.Document
# Zoom
self.zoom_level = 1.0
self.min_zoom = 0.25
self.max_zoom = 3.0
self.zoom_step = 0.25
# Rysowanie
self.drawing_mode = None
self.drawing_color = "red"
self.drawing_width = 2
self.temp_line = None
self.color_var = tk.StringVar(value="red")
self.zoom_label = None
# Tło
self.bg_color = "#f5f5f5"
self.root.configure(bg=self.bg_color)
self.setup_ui()
self.create_menu()
self.create_context_menu()
self.save_state("Start programu")
# Handler zamknięcia okna
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
def setup_ui(self):
main_container = tk.Frame(self.root, bg=self.bg_color)
main_container.pack(fill=tk.BOTH, expand=True)
# Belka z ikonami narzędzi
toolbar = tk.Frame(main_container, bg="#d0d0d0", bd=1, relief=tk.RAISED)
toolbar.pack(side=tk.TOP, fill=tk.X, padx=5, pady=5)
# Ikony Edycja (mniejsze)
tools = [
("⟲", lambda: self.rotate_selected(-90), "Obróć -90°"),
("⟳", lambda: self.rotate_selected(90), "Obróć +90°"),
("⟲180", lambda: self.rotate_selected(180), "Obróć 180°"),
("⇆", self.mirror_horizontal, "Lustro poziome"),
("⇅", self.mirror_vertical, "Lustro pionowe"),
("+", self.add_pages, "Dodaj strony"),
("−", self.delete_selected, "Usuń stronę"),
("↑", lambda: self.move_selected(-1), "W górę"),
("↓", lambda: self.move_selected(1), "W dół")
]
for icon, cmd, tip in tools:
lbl = tk.Label(toolbar, text=icon, font=("Arial", 10, "bold"), bg="#d0d0d0", cursor="hand2", padx=4, pady=1)
lbl.pack(side=tk.LEFT, padx=1)
lbl.bind("<Button-1>", lambda e, c=cmd: c())
ToolTip(lbl, tip)
# Separator
tk.Label(toolbar, text="|", bg="#d0d0d0", font=("Arial", 10)).pack(side=tk.LEFT, padx=4)
# Ikony Widok (bez zoom)
view_tools = [
("◀", self.prev_page, "Poprzednia"),
("▶", self.next_page, "Następna")
]
for icon, cmd, tip in view_tools:
lbl = tk.Label(toolbar, text=icon, font=("Arial", 10, "bold"), bg="#d0d0d0", cursor="hand2", padx=4, pady=1)
lbl.pack(side=tk.LEFT, padx=1)
lbl.bind("<Button-1>", lambda e, c=cmd: c())
ToolTip(lbl, tip)
# Separator i zoom
tk.Label(toolbar, text="|", bg="#d0d0d0", font=("Arial", 10)).pack(side=tk.LEFT, padx=4)
self.zoom_label = tk.Label(toolbar, text="100%", bg="#d0d0d0", font=("Arial", 9, "bold"), width=5)
self.zoom_label.pack(side=tk.LEFT, padx=2)
# Główny panel
content = tk.PanedWindow(main_container, orient=tk.HORIZONTAL, bg=self.bg_color)
content.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# Lewy panel
left_frame = tk.Frame(content, bg=self.bg_color)
content.add(left_frame, minsize=280)
tk.Label(left_frame, text="Strony dokumentu:", bg=self.bg_color, font=("Arial", 10, "bold")).pack(anchor=tk.W, pady=(0, 5))
list_frame = tk.Frame(left_frame)
list_frame.pack(fill=tk.BOTH, expand=True)
scrollbar = ttk.Scrollbar(list_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.tree = ttk.Treeview(list_frame, yscrollcommand=scrollbar.set, selectmode="extended", height=18)
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=self.tree.yview)
self.tree["columns"] = ("Lp", "Obrót", "Lustro")
self.tree.column("#0", width=0, stretch=False)
self.tree.column("Lp", width=40, anchor=tk.CENTER)
self.tree.column("Obrót", width=50, anchor=tk.CENTER)
self.tree.column("Lustro", width=50, anchor=tk.CENTER)
self.tree.heading("Lp", text="#")
self.tree.heading("Obrót", text="Obrót")
self.tree.heading("Lustro", text="Lustro")
self.tree.bind("<<TreeviewSelect>>", self.on_select_page)
self.tree.bind("<Double-1>", self.on_double_click)
# Info
self.info_label = tk.Label(left_frame, text="Otwórz plik PDF", bg="#e8e8e8", font=("Arial", 9), relief=tk.SUNKEN, anchor=tk.W)
self.info_label.pack(fill=tk.X, pady=(5, 0))
# Prawy panel - podgląd
right_frame = tk.Frame(content, bg="#d0d0d0")
content.add(right_frame, minsize=600)
# Canvas podglądu
self.canvas = tk.Canvas(right_frame, bg="#c0c0c0", highlightthickness=0, cursor="crosshair")
self.canvas.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# Bindings
self.canvas.bind("<Button-1>", self.on_canvas_click)
self.canvas.bind("<B1-Motion>", self.on_canvas_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_canvas_release)
# Status bar
self.status_bar = tk.Label(main_container, text="Gotowy", bg="#e8e8e8", anchor=tk.W, relief=tk.SUNKEN, font=("Arial", 9))
self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)
def add_toolbar_button(self, parent, text, command, tooltip):
btn = tk.Button(parent, text=text, command=command, font=("Arial", 9, "bold"),
relief=tk.RAISED, bd=1, padx=8, pady=4, bg="white", width=7)
btn.pack(side=tk.LEFT, padx=2, pady=3)
ToolTip(btn, tooltip)
return btn
def add_separator(self, parent):
sep = ttk.Separator(parent, orient=tk.VERTICAL)
sep.pack(side=tk.LEFT, fill=tk.Y, padx=6, pady=5)
def create_menu(self):
menubar = tk.Menu(self.root)
self.root.config(menu=menubar)
# Plik
file_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Plik", menu=file_menu, font=("Arial", 10))
file_menu.add_command(label="Otwórz PDF...", command=self.open_pdf, accelerator="Ctrl+O", font=("Arial", 9))
file_menu.add_command(label="Zapisz PDF jako...", command=self.save_pdf, accelerator="Ctrl+S", font=("Arial", 9))
file_menu.add_separator()
file_menu.add_command(label="Eksport do JPG...", command=lambda: self.export_image("jpg"), font=("Arial", 9))
file_menu.add_command(label="Eksport do PNG...", command=lambda: self.export_image("png"), font=("Arial", 9))
file_menu.add_command(label="Eksport do TXT...", command=self.export_txt, font=("Arial", 9))
if DOCX_AVAILABLE:
file_menu.add_command(label="Eksport do DOCX...", command=self.export_docx, font=("Arial", 9))
# Submenu Historia
self.hist_menu = tk.Menu(file_menu, tearoff=0)
file_menu.add_cascade(label="Historia", menu=self.hist_menu, font=("Arial", 9))
self.hist_menu.add_command(label="(pusta)", state=tk.DISABLED)
file_menu.add_separator()
file_menu.add_command(label="Wyczyść historię", command=self.clear_history, font=("Arial", 9))
file_menu.add_separator()
file_menu.add_command(label="Wyjście", command=self.root.quit, font=("Arial", 9))
# Edycja
edit_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Edycja", menu=edit_menu, font=("Arial", 10))
edit_menu.add_command(label="Cofnij", command=self.undo, accelerator="Ctrl+Z", font=("Arial", 9))
edit_menu.add_command(label="Powtórz", command=self.redo, accelerator="Ctrl+Y", font=("Arial", 9))
edit_menu.add_separator()
edit_menu.add_command(label="Obróć -90°", command=lambda: self.rotate_selected(-90), font=("Arial", 9))
edit_menu.add_command(label="Obróć +90°", command=lambda: self.rotate_selected(90), font=("Arial", 9))
edit_menu.add_command(label="Obróć 180°", command=lambda: self.rotate_selected(180), font=("Arial", 9))
edit_menu.add_separator()
edit_menu.add_command(label="Lustro poziome", command=self.mirror_horizontal, font=("Arial", 9))
edit_menu.add_command(label="Lustro pionowe", command=self.mirror_vertical, font=("Arial", 9))
edit_menu.add_separator()
edit_menu.add_command(label="Dodaj strony...", command=self.add_pages, font=("Arial", 9))
edit_menu.add_command(label="Usuń zaznaczone", command=self.delete_selected, font=("Arial", 9))
# Widok
view_menu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label="Widok", menu=view_menu, font=("Arial", 10))
view_menu.add_command(label="Następna strona", command=self.next_page, accelerator="Page Down", font=("Arial", 9))
view_menu.add_command(label="Poprzednia strona", command=self.prev_page, accelerator="Page Up", font=("Arial", 9))
# Historia - tylko wyczyść (w menu Plik)
# (Narzędzia usunięte)
# Keyboard shortcuts
self.root.bind('<Control-o>', lambda e: self.open_pdf())
self.root.bind('<Control-s>', lambda e: self.save_pdf())
self.root.bind('<Control-z>', lambda e: self.undo())
self.root.bind('<Control-y>', lambda e: self.redo())
self.root.bind('<Control-plus>', lambda e: self.zoom_in())
self.root.bind('<Control-minus>', lambda e: self.zoom_out())
self.root.bind('<Control-0>', lambda e: self.zoom_reset())
self.root.bind('<Prior>', lambda e: self.prev_page())
self.root.bind('<Next>', lambda e: self.next_page())
def create_context_menu(self):
# Menu podręczne (prawy przycisk)
self.context_menu = tk.Menu(self.root, tearoff=0)
# Edycja
edit_menu = tk.Menu(self.context_menu, tearoff=0)
self.context_menu.add_cascade(label="✏️ Edycja", menu=edit_menu)
edit_menu.add_command(label="↩️ Cofnij (Ctrl+Z)", command=self.undo)
edit_menu.add_command(label="↪️ Powtórz (Ctrl+Y)", command=self.redo)
edit_menu.add_separator()
edit_menu.add_command(label="🔄 Obróć -90°", command=lambda: self.rotate_selected(-90))
edit_menu.add_command(label="🔄 Obróć +90°", command=lambda: self.rotate_selected(90))
edit_menu.add_command(label="🔄 Obróć 180°", command=lambda: self.rotate_selected(180))
edit_menu.add_separator()
edit_menu.add_command(label="↔️ Lustro poziome", command=self.mirror_horizontal)
edit_menu.add_command(label="↕️ Lustro pionowe", command=self.mirror_vertical)
edit_menu.add_separator()
edit_menu.add_command(label="➕ Dodaj strony", command=self.add_pages)
edit_menu.add_command(label="➖ Usuń stronę", command=self.delete_selected)
# Widok
view_menu = tk.Menu(self.context_menu, tearoff=0)
self.context_menu.add_cascade(label="👁️ Widok", menu=view_menu)
view_menu.add_command(label="⬆️ Poprzednia strona", command=self.prev_page)
view_menu.add_command(label="⬇️ Następna strona", command=self.next_page)
# Bind right-click
self.root.bind('<Button-3>', self.show_context_menu)
def clear_history(self):
"""Wyczyść historię"""
self.history = []
self.history_index = -1
self.save_state("Start")
def close_source_docs(self):
"""Zamknij wszystkie źródłowe dokumenty"""
for doc in self.source_docs.values():
try:
doc.close()
except:
pass
self.source_docs = {}
def on_closing(self):
"""Zamknij aplikację i zwolnij zasoby"""
if self.doc:
try:
self.doc.close()
except:
pass
self.close_source_docs()
self.root.destroy()
def show_context_menu(self, event):
self.context_menu.post(event.x_root, event.y_root)
def update_hist_menu(self):
"""Aktualizuj submenu historii w menu Plik"""
self.hist_menu.delete(0, tk.END)
if not self.history:
self.hist_menu.add_command(label="(pusta)", state=tk.DISABLED)
return
for i, state in enumerate(self.history):
marker = "►" if i == self.history_index else " "
self.hist_menu.add_command(label=f"{marker} {state['action']}",
command=lambda idx=i: self.goto_history(idx))
def goto_history(self, idx):
"""Idź do konkretnego momentu w historii"""
if 0 <= idx < len(self.history):
self.history_index = idx
self.restore_state(self.history[idx])
self.set_status(f"Przywrócono: {self.history[idx]['action']}")
def save_state(self, action_name):
"""Zapisz pełny stan do historii"""
state = {
'action': action_name,
'pages': []
}
for p in self.pages_list:
page_data = {
'page_num': p['page_num'],
'rotation': p['rotation'],
'mirror_h': p.get('mirror_h', False),
'mirror_v': p.get('mirror_v', False),
'drawings': list(p.get('drawings', []))
}
if 'source_doc' in p:
page_data['source_doc_path'] = p.get('source_doc_path', '')
page_data['source_page'] = p['source_page']
state['pages'].append(page_data)
# Jeśli jesteśmy na końcu historii, dodaj nowy stan
if self.history_index == len(self.history) - 1:
self.history.append(state)
self.history_index += 1
else:
# Jesteśmy w środku - zastąp obecny stan i kasuj przyszłe
self.history_index += 1
self.history = self.history[:self.history_index]
self.history.append(state)
# Ogranicz rozmiar historii
if len(self.history) > self.max_history:
excess = len(self.history) - self.max_history
self.history = self.history[excess:]
self.history_index -= excess
self.update_hist_menu()
def restore_state(self, state):
"""Przywróć stan z historii"""
self.pages_list = []
# Zamknij poprzednie dokumenty źródłowe przed otwarciem nowych
self.close_source_docs()
for p in state['pages']:
page_data = {
'page_num': p['page_num'],
'rotation': p['rotation'],
'mirror_h': p.get('mirror_h', False),
'mirror_v': p.get('mirror_v', False),
'drawings': p.get('drawings', [])
}
if 'source_doc_path' in p and p['source_doc_path']:
try:
page_data['source_doc'] = fitz.open(p['source_doc_path'])
page_data['source_page'] = p['source_page']
except Exception as e:
print(f"Nie można załadować strony z {p.get('source_doc_path', 'unknown')}: {e}")
messagebox.showwarning("Ostrzeżenie", f"Nie można załadować strony z pliku: {os.path.basename(p.get('source_doc_path', 'unknown'))}")
self.pages_list.append(page_data)
self.refresh_list()
if self.selected_page_idx is not None and self.selected_page_idx < len(self.pages_list):
self.render_preview(self.selected_page_idx)
def undo(self):
if self.history_index > 0:
self.history_index -= 1
self.restore_state(self.history[self.history_index])
self.set_status(f"Cofnięto: {self.history[self.history_index]['action']}")
def redo(self):
if self.history_index < len(self.history) - 1:
self.history_index += 1
self.restore_state(self.history[self.history_index])
self.set_status(f"Powtórzono: {self.history[self.history_index]['action']}")
def set_status(self, text):
self.status_bar.config(text=text)
self.root.update_idletasks()
def open_pdf(self):
file_path = filedialog.askopenfilename(
title="Wybierz plik PDF",
filetypes=[("PDF files", "*.pdf"), ("All files", "*.*")]
)
if not file_path:
return
try:
if self.doc:
self.doc.close()
# Zamknij źródłowe dokumenty
self.close_source_docs()
self.doc = fitz.open(file_path)
self.current_file_path = file_path
self.pages_list = []
for i in range(self.doc.page_count):
self.pages_list.append({
'page_num': i,
'rotation': 0,
'mirror_h': False,
'mirror_v': False,
'drawings': []
})
self.save_state(f"Otworzono: {os.path.basename(file_path)}")
self.refresh_list()
self.info_label.config(text=f"{os.path.basename(file_path)} | Stron: {len(self.pages_list)}")
if self.pages_list:
self.tree.selection_set(0)
self.on_select_page(None)
except Exception as e:
messagebox.showerror("Błąd", f"Nie udało się otworzyć:\n{e}")
def refresh_list(self):
for item in self.tree.get_children():
self.tree.delete(item)
for i, p in enumerate(self.pages_list):
rot = f"{p['rotation']}°" if p['rotation'] else "0°"
mirror = "H" if p['mirror_h'] else ("V" if p['mirror_v'] else "")
self.tree.insert("", tk.END, iid=i, values=(i+1, rot, mirror))
def on_select_page(self, event):
selection = self.tree.selection()
if selection:
self.selected_page_idx = int(selection[0])
self.render_preview(self.selected_page_idx)
def on_double_click(self, event):
idx = self.tree.selection()
if idx:
idx = int(idx[0])
dialog = tk.Toplevel(self.root)
dialog.title(f"Strona {idx+1}")
dialog.geometry("220x180")
dialog.transient(self.root)
dialog.grab_set()
tk.Label(dialog, text="Obrót:").pack(anchor=tk.W, padx=10, pady=5)
rot_var = tk.IntVar(value=self.pages_list[idx]['rotation'])
for deg, txt in [(0,"0°"),(90,"90°"),(180,"180°"),(270,"270°")]:
tk.Radiobutton(dialog, text=txt, variable=rot_var, value=deg).pack(anchor=tk.W, padx=20)
tk.Label(dialog, text="Odbicie:").pack(anchor=tk.W, padx=10, pady=5)
h_var = tk.BooleanVar(value=self.pages_list[idx]['mirror_h'])
tk.Checkbutton(dialog, text="Poziome", variable=h_var).pack(anchor=tk.W, padx=20)
v_var = tk.BooleanVar(value=self.pages_list[idx]['mirror_v'])
tk.Checkbutton(dialog, text="Pionowe", variable=v_var).pack(anchor=tk.W, padx=20)
def apply():
self.pages_list[idx]['rotation'] = rot_var.get()
self.pages_list[idx]['mirror_h'] = h_var.get()
self.pages_list[idx]['mirror_v'] = v_var.get()
self.save_state("Edycja strony")
self.refresh_list()
self.render_preview(idx)
dialog.destroy()
tk.Button(dialog, text="Zastosuj", command=apply).pack(pady=15)
def render_preview(self, idx):
if not self.doc or idx >= len(self.pages_list):
return
try:
p = self.pages_list[idx]
page = self.doc.load_page(p['page_num'])
zoom = 1.5 * self.zoom_level
mat = fitz.Matrix(zoom, zoom)
if p['rotation']:
mat = fitz.Matrix(zoom, zoom).prerotate(p['rotation'])
pix = page.get_pixmap(matrix=mat)
img_data = pix.tobytes("png")
pil_img = Image.open(io.BytesIO(img_data))
if p['mirror_h']:
pil_img = pil_img.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
if p['mirror_v']:
pil_img = pil_img.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
cw = self.canvas.winfo_width() or 600
ch = self.canvas.winfo_height() or 700
iw, ih = pil_img.size
scale = min(cw/iw, ch/ih) * 0.9
new_size = (int(iw*scale), int(ih*scale))
pil_img = pil_img.resize(new_size, Image.Resampling.LANCZOS)
self.preview_image = ImageTk.PhotoImage(pil_img)
self.canvas.delete("all")
cx = (cw - new_size[0]) // 2
cy = (ch - new_size[1]) // 2
self.canvas.create_image(cx + new_size[0]//2, cy + new_size[1]//2, image=self.preview_image, anchor=tk.CENTER)
# Narysuj zapisane rysunki
self.redraw_saved(idx, cx, cy, scale)
# Info
draws = len(p.get('drawings', []))
self.info_label.config(text=f"Strona {idx+1}/{len(self.pages_list)} | Rysunki: {draws}")
except Exception as e:
print(f"Błąd: {e}")
def redraw_saved(self, idx, ox, oy, scale):
drawings = self.pages_list[idx].get('drawings', [])
for d in drawings:
color = d.get('color', 'red')
width = d.get('width', 2)
if d['type'] == 'line':
x1, y1 = ox + d['x1']*scale, oy + d['y1']*scale
x2, y2 = ox + d['x2']*scale, oy + d['y2']*scale
self.canvas.create_line(x1, y1, x2, y2, fill=color, width=width)
elif d['type'] == 'rectangle':
x1, y1 = ox + d['x1']*scale, oy + d['y1']*scale
x2, y2 = ox + d['x2']*scale, oy + d['y2']*scale
self.canvas.create_rectangle(x1, y1, x2, y2, outline=color, width=width)
elif d['type'] == 'ellipse':
x1, y1 = ox + d['x1']*scale, oy + d['y1']*scale
x2, y2 = ox + d['x2']*scale, oy + d['y2']*scale
self.canvas.create_oval(x1, y1, x2, y2, outline=color, width=width)
elif d['type'] == 'pen':
pts = []
for px, py in d['points']:
pts.extend([ox + px*scale, oy + py*scale])
self.canvas.create_line(pts, fill=color, width=width, smooth=True)
def rotate_selected(self, angle):
sel = self.tree.selection()
if not sel:
messagebox.showwarning("Wybierz strony", "Zaznacz strony do obrócenia")
return
for item in sel:
idx = int(item)
self.pages_list[idx]['rotation'] = (self.pages_list[idx]['rotation'] + angle) % 360
self.save_state(f"Obrót {angle}°")
self.refresh_list()
if self.selected_page_idx is not None:
self.render_preview(self.selected_page_idx)
def mirror_horizontal(self):
sel = self.tree.selection()
if not sel:
messagebox.showwarning("Wybierz strony", "Zaznacz strony")
return
for item in sel:
idx = int(item)
self.pages_list[idx]['mirror_h'] = not self.pages_list[idx]['mirror_h']
self.save_state("Lustro poziome")
self.refresh_list()
if self.selected_page_idx is not None:
self.render_preview(self.selected_page_idx)
def mirror_vertical(self):
sel = self.tree.selection()
if not sel:
messagebox.showwarning("Wybierz strony", "Zaznacz strony")
return
for item in sel:
idx = int(item)
self.pages_list[idx]['mirror_v'] = not self.pages_list[idx]['mirror_v']
self.save_state("Lustro pionowe")
self.refresh_list()
if self.selected_page_idx is not None:
self.render_preview(self.selected_page_idx)
def delete_selected(self):
sel = self.tree.selection()
if not sel:
messagebox.showwarning("Wybierz strony", "Zaznacz strony do usunięcia")
return
if not messagebox.askyesno("Potwierdzenie", f"Usunąć {len(sel)} stron?"):
return
indices = sorted([int(i) for i in sel], reverse=True)
for idx in indices:
self.pages_list.pop(idx)
self.save_state(f"Usunięto {len(indices)} stron")
self.refresh_list()
self.selected_page_idx = None
self.canvas.delete("all")
def move_selected(self, direction):
sel = self.tree.selection()
if not sel or len(sel) > 1:
messagebox.showwarning("Wybierz jedną stronę")
return
idx = int(sel[0])
new_idx = idx + direction
if 0 <= new_idx < len(self.pages_list):
self.pages_list[idx], self.pages_list[new_idx] = self.pages_list[new_idx], self.pages_list[idx]
self.save_state("Zmiana kolejności")
self.refresh_list()
self.tree.selection_set(new_idx)
self.selected_page_idx = new_idx
self.render_preview(new_idx)
def add_pages(self):
path = filedialog.askopenfilename(title="Wybierz PDF", filetypes=[("PDF files", "*.pdf")])
if not path:
return
try:
# Otwórz lub użyj istniejącego dokumentu źródłowego
if path not in self.source_docs:
self.source_docs[path] = fitz.open(path)
add_doc = self.source_docs[path]
for i in range(add_doc.page_count):
self.pages_list.append({
'page_num': i,
'source_doc': add_doc,
'source_doc_path': path,
'source_page': i,
'rotation': 0,
'mirror_h': False,
'mirror_v': False,
'drawings': []
})
self.save_state(f"Dodano {add_doc.page_count} stron")
self.refresh_list()
messagebox.showinfo("Sukces", f"Dodano {add_doc.page_count} stron")
except Exception as e:
messagebox.showerror("Błąd", str(e))
# Zoom
def zoom_in(self):
if self.zoom_level < self.max_zoom:
self.zoom_level = min(self.zoom_level + self.zoom_step, self.max_zoom)
self.zoom_label.config(text=f"{int(self.zoom_level*100)}%")
if self.selected_page_idx is not None:
self.render_preview(self.selected_page_idx)
self.set_status(f"Zoom: {int(self.zoom_level*100)}%")
def zoom_out(self):
if self.zoom_level > self.min_zoom:
self.zoom_level = max(self.zoom_level - self.zoom_step, self.min_zoom)
self.zoom_label.config(text=f"{int(self.zoom_level*100)}%")
if self.selected_page_idx is not None:
self.render_preview(self.selected_page_idx)
self.set_status(f"Zoom: {int(self.zoom_level*100)}%")
def zoom_reset(self):
self.zoom_level = 1.0
self.zoom_label.config(text="100%")
if self.selected_page_idx is not None:
self.render_preview(self.selected_page_idx)
self.set_status("Zoom: 100%")
def next_page(self):
if self.selected_page_idx is not None and self.selected_page_idx < len(self.pages_list) - 1:
self.tree.selection_set(self.selected_page_idx + 1)
self.on_select_page(None)
def prev_page(self):
if self.selected_page_idx is not None and self.selected_page_idx > 0:
self.tree.selection_set(self.selected_page_idx - 1)
self.on_select_page(None)
# Rysowanie
def set_drawing_mode(self, mode):
self.drawing_mode = mode
self.canvas.config(cursor="crosshair")
self.set_status(f"Tryb: {mode}")
def set_selection_mode(self):
self.drawing_mode = 'select'
self.canvas.config(cursor="arrow")
self.set_status("Tryb zaznaczania - przeciągnij aby zaznaczyć obszar")
def on_canvas_click(self, event):
if self.drawing_mode == 'select':
# Zaznaczanie obszaru na podglądzie
self.start_x = event.x
self.start_y = event.y
self.canvas.delete('selection')
return
if not self.drawing_mode or self.selected_page_idx is None:
return
self.start_x = event.x
self.start_y = event.y
def on_canvas_drag(self, event):
if self.drawing_mode == 'select' and self.start_x is not None:
# Rysowanie prostokąta zaznaczenia
self.canvas.delete('selection')
self.canvas.create_rectangle(self.start_x, self.start_y, event.x, event.y,
outline='blue', width=2, tags='selection')
return
if not self.drawing_mode or self.start_x is None:
return
if self.temp_line:
self.canvas.delete(self.temp_line)
color = self.color_var.get()
if self.drawing_mode == 'line':
self.temp_line = self.canvas.create_line(self.start_x, self.start_y, event.x, event.y,
fill=color, width=self.drawing_width)
elif self.drawing_mode == 'rectangle':
self.temp_line = self.canvas.create_rectangle(self.start_x, self.start_y, event.x, event.y,
outline=color, width=self.drawing_width)
elif self.drawing_mode == 'ellipse':
self.temp_line = self.canvas.create_oval(self.start_x, self.start_y, event.x, event.y,
outline=color, width=self.drawing_width)
def on_canvas_release(self, event):
if self.drawing_mode == 'select':
# Zaznaczanie zakończone
self.canvas.delete('selection')
self.start_x = None
self.start_y = None
return
if not self.drawing_mode or self.start_x is None or self.selected_page_idx is None:
return
if self.temp_line:
self.canvas.delete(self.temp_line)
self.temp_line = None
# Konwersja do PDF
cw = self.canvas.winfo_width() or 600
ch = self.canvas.winfo_height() or 700
if self.preview_image:
iw = self.preview_image.width()
ih = self.preview_image.height()
ox = (cw - iw) // 2
oy = (ch - ih) // 2
# Pobierz wymiary strony PDF
page = self.doc.load_page(self.pages_list[self.selected_page_idx]['page_num'])
pw = page.rect.width
ph = page.rect.height
# Skala PDF -> canvas
pdf_scale = iw / (pw * 1.5 * self.zoom_level)
# canvas -> PDF
x1 = (self.start_x - ox) / pdf_scale
y1 = (self.start_y - oy) / pdf_scale
x2 = (event.x - ox) / pdf_scale
y2 = (event.y - oy) / pdf_scale
drawing = {
'type': self.drawing_mode,
'x1': min(x1, x2), 'y1': min(y1, y2),
'x2': max(x1, x2), 'y2': max(y1, y2),
'color': self.color_var.get(),
'width': self.drawing_width
}
if self.drawing_mode == 'pen':
drawing['points'] = [(x1, y1), (x2, y2)]
if 'drawings' not in self.pages_list[self.selected_page_idx]:
self.pages_list[self.selected_page_idx]['drawings'] = []
self.pages_list[self.selected_page_idx]['drawings'].append(drawing)
self.save_state(f"Dodano: {self.drawing_mode}")
self.render_preview(self.selected_page_idx)
self.start_x = None
self.start_y = None
def export_image(self, fmt):
sel = self.tree.selection()
if not sel:
messagebox.showwarning("Wybierz strony")
return
ext = f".{fmt}"
path = filedialog.asksaveasfilename(title=f"Eksport {fmt.upper()}", defaultextension=ext,
filetypes=[(f"{fmt.upper()} files", f"*{ext}")])
if not path:
return
try:
if len(sel) == 1:
idx = int(sel[0])
page = self.doc.load_page(self.pages_list[idx]['page_num'])
zoom = 2.0
rot = self.pages_list[idx]['rotation']
mat = fitz.Matrix(zoom, zoom).prerotate(rot) if rot else fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat)
if fmt == "jpg":
img = Image.open(io.BytesIO(pix.tobytes("png")))
img.save(path, "JPEG", quality=95)
else:
pix.save(path)
else:
base = os.path.splitext(path)[0]
for item in sel:
idx = int(item)
page = self.doc.load_page(self.pages_list[idx]['page_num'])
pix = page.get_pixmap(matrix=fitz.Matrix(2.0, 2.0))
out_path = f"{base}_{idx+1}{ext}"
if fmt == "jpg":
img = Image.open(io.BytesIO(pix.tobytes("png")))
img.save(out_path, "JPEG", quality=95)
else:
pix.save(out_path)
messagebox.showinfo("Sukces", f"Zapisano: {path}")
self.save_state(f"Eksport {fmt.upper()}")
except Exception as e:
messagebox.showerror("Błąd", str(e))
def export_txt(self):
sel = self.tree.selection()
if not sel:
messagebox.showwarning("Wybierz strony")
return
path = filedialog.asksaveasfilename(title="Eksport TXT", defaultextension=".txt",
filetypes=[("Text files", "*.txt")])
if not path:
return
try:
with open(path, "w", encoding="utf-8") as f:
for item in sel:
idx = int(item)
page = self.doc.load_page(self.pages_list[idx]['page_num'])
f.write(f"{'='*50}\nSTRONA {idx+1}\n{'='*50}\n\n")
f.write(page.get_text())
f.write("\n\n")
messagebox.showinfo("Sukces", f"Zapisano: {path}")
self.save_state("Eksport TXT")
except Exception as e:
messagebox.showerror("Błąd", str(e))
def export_docx(self):
if not DOCX_AVAILABLE:
messagebox.showerror("Błąd", "Biblioteka python-docx niedostępna")
return
sel = self.tree.selection()
if not sel:
messagebox.showwarning("Wybierz strony")
return
path = filedialog.asksaveasfilename(title="Eksport DOCX", defaultextension=".docx",
filetypes=[("DOCX files", "*.docx")])
if not path:
return
try:
doc = Document()
for item in sel:
idx = int(item)
page = self.doc.load_page(self.pages_list[idx]['page_num'])
doc.add_heading(f"Strona {idx+1}", 2)
doc.add_paragraph(page.get_text())
doc.add_page_break()
doc.save(path)
messagebox.showinfo("Sukces", f"Zapisano: {path}")
self.save_state("Eksport DOCX")
except Exception as e:
messagebox.showerror("Błąd", str(e))
def save_pdf(self):
if not self.pages_list:
messagebox.showwarning("Brak stron")
return
path = filedialog.asksaveasfilename(title="Zapisz PDF", defaultextension=".pdf",
filetypes=[("PDF files", "*.pdf")])
if not path:
return
try:
new_doc = fitz.open()
try:
for p in self.pages_list:
if 'source_doc' in p:
src = p['source_doc'].load_page(p['source_page'])
page = new_doc.new_page(width=src.rect.width, height=src.rect.height)
page.show_pdf_page(page.rect, p['source_doc'], p['source_page'])
else:
src = self.doc.load_page(p['page_num'])
page = new_doc.new_page(width=src.rect.width, height=src.rect.height)
page.show_pdf_page(page.rect, self.doc, p['page_num'])
# Rysunki
for d in p.get('drawings', []):
color_str = d.get('color', 'red')
if color_str.startswith('#') and len(color_str) == 7:
color = tuple(int(color_str.lstrip('#')[i:i+2], 16)/255 for i in (0, 2, 4))
else:
color = (1, 0, 0) # domyślny czerwony
width = d.get('width', 2)
if d['type'] == 'line':
page.draw_line(fitz.Point(d['x1'], d['y1']), fitz.Point(d['x2'], d['y2']), color=color, width=width)
elif d['type'] == 'rectangle':
page.draw_rect(fitz.Rect(d['x1'], d['y1'], d['x2'], d['y2']), color=color, width=width)
elif d['type'] == 'ellipse':
page.draw_ellipse(fitz.Rect(d['x1'], d['y1'], d['x2'], d['y2']), color=color, width=width)
if p['rotation']:
page.set_rotation(p['rotation'])
new_doc.save(path)
messagebox.showinfo("Sukces", f"Zapisano: {path}")
self.save_state("Zapis PDF")
finally:
new_doc.close()
except Exception as e:
messagebox.showerror("Błąd", str(e))
import traceback
traceback.print_exc()
if __name__ == "__main__":
root = tk.Tk()
app = PDFEditorApp(root)
root.mainloop()