SafePDF 1.0.11__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. SafePDF/__init__.py +10 -0
  2. SafePDF/ctrl/__init__.py +0 -0
  3. SafePDF/ctrl/language_manager.py +69 -0
  4. SafePDF/ctrl/safe_pdf_controller.py +469 -0
  5. SafePDF/logger/__init__.py +0 -0
  6. SafePDF/logger/logging_config.py +94 -0
  7. SafePDF/ops/__init__.py +0 -0
  8. SafePDF/ops/license_manager.py +247 -0
  9. SafePDF/ops/pdf2docx.py +157 -0
  10. SafePDF/ops/pdf2jpeg.py +116 -0
  11. SafePDF/ops/pdf_compress.py +282 -0
  12. SafePDF/ops/pdf_merge.py +104 -0
  13. SafePDF/ops/pdf_operations.py +563 -0
  14. SafePDF/ops/pdf_rotate.py +102 -0
  15. SafePDF/ops/pdf_split.py +178 -0
  16. SafePDF/ops/updates.py +308 -0
  17. SafePDF/safe_pdf_app.py +121 -0
  18. SafePDF/test/__init__.py +0 -0
  19. SafePDF/test/test_compression.py +79 -0
  20. SafePDF/test/test_pro_dialog.py +45 -0
  21. SafePDF/text/de/help_content.txt +58 -0
  22. SafePDF/text/de/pro_features.txt +9 -0
  23. SafePDF/text/de/ui.json +260 -0
  24. SafePDF/text/de/welcome_content.txt +24 -0
  25. SafePDF/text/en/help_content.txt +42 -0
  26. SafePDF/text/en/pro_features.txt +8 -0
  27. SafePDF/text/en/ui.json +260 -0
  28. SafePDF/text/en/welcome_content.txt +25 -0
  29. SafePDF/text/tr/help_content.txt +53 -0
  30. SafePDF/text/tr/pro_features.txt +8 -0
  31. SafePDF/text/tr/ui.json +260 -0
  32. SafePDF/text/tr/welcome_content.txt +24 -0
  33. SafePDF/ui/__init__.py +11 -0
  34. SafePDF/ui/common_elements.py +40 -0
  35. SafePDF/ui/help_ui.py +233 -0
  36. SafePDF/ui/language_elements.py +9 -0
  37. SafePDF/ui/operation_settings.py +377 -0
  38. SafePDF/ui/safe_pdf_ui.py +3497 -0
  39. SafePDF/ui/settings_ui.py +394 -0
  40. SafePDF/ui/tabs_manager.py +235 -0
  41. SafePDF/ui/update_ui.py +717 -0
  42. SafePDF/version.txt +34 -0
  43. safepdf-1.0.11.dist-info/METADATA +162 -0
  44. safepdf-1.0.11.dist-info/RECORD +48 -0
  45. safepdf-1.0.11.dist-info/WHEEL +5 -0
  46. safepdf-1.0.11.dist-info/entry_points.txt +2 -0
  47. safepdf-1.0.11.dist-info/licenses/LICENSE +674 -0
  48. safepdf-1.0.11.dist-info/top_level.txt +1 -0
@@ -0,0 +1,282 @@
1
+ """
2
+ PDF Compression Module for SafePDF
3
+ Handles all PDF compression operations
4
+ """
5
+
6
+ import tkinter as tk
7
+ from os import path as os_path
8
+ from pathlib import Path
9
+ from tkinter import Button, Label, Toplevel, messagebox
10
+ from typing import Tuple
11
+
12
+ from PIL import Image, ImageTk
13
+ from PyPDF2 import PdfReader, PdfWriter
14
+
15
+ from SafePDF.logger.logging_config import get_logger
16
+ from SafePDF.ui.common_elements import CommonElements
17
+
18
+
19
+ class PDFCompressor:
20
+ """Class handling PDF compression operations"""
21
+
22
+ def __init__(self, progress_callback=None, language_manager=None, atomic_write_file=None, validate_pdf=None):
23
+ """
24
+ Initialize PDF compressor
25
+
26
+ Args:
27
+ progress_callback: Function to call for progress updates (0-100)
28
+ language_manager: Language manager for localization
29
+ atomic_write_file: Function for atomic file writing
30
+ validate_pdf: Function to validate PDF files
31
+ """
32
+ self.progress_callback = progress_callback
33
+ self.language_manager = language_manager
34
+ self._atomic_write_file = atomic_write_file
35
+ self._validate_pdf = validate_pdf
36
+ self._cancel_requested = False
37
+ self.logger = get_logger("SafePDF.PDFCompress")
38
+
39
+ def update_progress(self, value):
40
+ """Update progress if callback is available"""
41
+ if self.progress_callback:
42
+ self.progress_callback(value)
43
+
44
+ def request_cancel(self):
45
+ """Request cancellation of a running operation."""
46
+ self._cancel_requested = True
47
+
48
+ def compress_pdf(self, input_path: str, output_path: str, quality: str = "medium") -> Tuple[bool, str]:
49
+ """
50
+ Compress PDF file
51
+
52
+ Args:
53
+ input_path: Input PDF file path
54
+ output_path: Output PDF file path
55
+ quality: Compression quality ("low", "medium", "high")
56
+
57
+ Returns:
58
+ Tuple of (success, message)
59
+ """
60
+ try:
61
+ if not PdfReader or not PdfWriter:
62
+ return False, self.language_manager.get(
63
+ "op_pypdf_unavailable", "PyPDF2/pypdf not available"
64
+ ) if self.language_manager else "PyPDF2/pypdf not available"
65
+
66
+ self.update_progress(5)
67
+
68
+ # Validate input file
69
+ if not os_path.exists(input_path):
70
+ return False, self.language_manager.get(
71
+ "op_input_file_not_exist", "Input file does not exist"
72
+ ) if self.language_manager else "Input file does not exist"
73
+
74
+ if self._validate_pdf and not self._validate_pdf(input_path):
75
+ return False, self.language_manager.get(
76
+ "op_invalid_pdf", "Input file is not a valid PDF"
77
+ ) if self.language_manager else "Input file is not a valid PDF"
78
+
79
+ # Use PyPDF2 stream compression approach
80
+ self.update_progress(10)
81
+ reader = PdfReader(input_path)
82
+ writer = PdfWriter()
83
+ total_pages = len(reader.pages)
84
+ for i, page in enumerate(reader.pages):
85
+ if self._cancel_requested:
86
+ return False, self.language_manager.get(
87
+ "op_cancelled", "Operation cancelled by user"
88
+ ) if self.language_manager else "Operation cancelled by user"
89
+ try:
90
+ page.compress_content_streams()
91
+ except Exception:
92
+ pass
93
+ writer.add_page(page)
94
+ self.update_progress(10 + (80 * i // max(1, total_pages)))
95
+
96
+ def _write_compressed(tmpf):
97
+ writer.write(tmpf)
98
+
99
+ if self._atomic_write_file:
100
+ self._atomic_write_file(output_path, _write_compressed)
101
+ else:
102
+ with open(output_path, "wb") as f:
103
+ _write_compressed(f)
104
+
105
+ self.update_progress(100)
106
+
107
+ # Compare sizes and warn if increased
108
+ if os_path.exists(output_path):
109
+ if self._validate_pdf and not self._validate_pdf(output_path):
110
+ return False, self.language_manager.get(
111
+ "op_invalid_output", "Compression completed but output file is invalid"
112
+ ) if self.language_manager else "Compression completed but output file is invalid"
113
+
114
+ original_size = os_path.getsize(input_path)
115
+ compressed_size = os_path.getsize(output_path)
116
+ if original_size == 0:
117
+ return False, self.language_manager.get(
118
+ "op_zero_size", "Original file size is zero. Cannot calculate compression."
119
+ ) if self.language_manager else "Original file size is zero. Cannot calculate compression."
120
+ if compressed_size < original_size:
121
+ compression_ratio = (1 - (compressed_size / original_size)) * 100
122
+ success_msg = (
123
+ self.language_manager.get(
124
+ "op_compress_success",
125
+ "PDF compressed successfully. Quality: {quality}. Size reduced by {compression_ratio:.1f}%",
126
+ )
127
+ if self.language_manager
128
+ else "PDF compressed successfully. Quality: {quality}. Size reduced by {compression_ratio:.1f}%"
129
+ )
130
+ return True, success_msg.format(quality=quality, compression_ratio=abs(compression_ratio))
131
+ else:
132
+ # Show warning immediately when compression doesn't reduce size
133
+ self.show_compression_error_popup()
134
+ if compressed_size == original_size:
135
+ return (
136
+ False,
137
+ self.language_manager.get(
138
+ "op_no_compression",
139
+ "No size reduction achieved. Please try a different quality setting or use 'Microsoft Print to PDF' from the print dialog.",
140
+ )
141
+ if self.language_manager
142
+ else "No size reduction achieved. Please try a different quality setting or use 'Microsoft Print to PDF' from the print dialog.",
143
+ )
144
+ else:
145
+ increase_pct = ((compressed_size / original_size) - 1) * 100
146
+ error_msg = (
147
+ self.language_manager.get(
148
+ "op_compress_increased",
149
+ "Compression increased file size by {increase_pct:.1f}%. Please try a different quality setting.",
150
+ )
151
+ if self.language_manager
152
+ else "Compression increased file size by {increase_pct:.1f}%. Please try a different quality setting."
153
+ )
154
+ return False, error_msg.format(increase_pct=increase_pct)
155
+
156
+ return False, self.language_manager.get(
157
+ "op_invalid_output", "Compression completed but output file is invalid"
158
+ ) if self.language_manager else "Compression completed but output file is invalid"
159
+
160
+ except Exception as e:
161
+ error_msg = (
162
+ self.language_manager.get("op_compress_failed", "Compression failed: {error}")
163
+ if self.language_manager
164
+ else "Compression failed: {error}"
165
+ )
166
+ return False, error_msg.format(error=str(e))
167
+
168
+ def show_compression_error_popup(self):
169
+ """
170
+ Show a custom popup with compression error gif when no compression is achieved
171
+ """
172
+ try:
173
+ if not tk or not Toplevel or not Image:
174
+ return
175
+
176
+ # Create popup window
177
+ popup = Toplevel()
178
+ popup.title(
179
+ self.language_manager.get("op_compression_info", "Compression Info")
180
+ if self.language_manager
181
+ else "Compression Info"
182
+ )
183
+ popup.geometry("550x400")
184
+ popup.resizable(False, False)
185
+ # Disable menu bar
186
+ popup.overrideredirect(False)
187
+
188
+ # Center the window
189
+ popup.transient()
190
+ popup.grab_set()
191
+
192
+ # Load and display the gif using package-relative path
193
+ module_dir = Path(__file__).parent
194
+ gif_path = module_dir / "assets" / "compression_err.gif"
195
+ if gif_path.exists():
196
+ try:
197
+ # Load the GIF and handle animation
198
+ gif_image = Image.open(str(gif_path))
199
+ frames = []
200
+
201
+ try:
202
+ # Extract all frames from the GIF
203
+ while True:
204
+ frames.append(ImageTk.PhotoImage(gif_image.copy()))
205
+ gif_image.seek(gif_image.tell() + 1)
206
+ except EOFError:
207
+ pass # End of frames
208
+
209
+ # Display animated GIF
210
+ img_label = Label(popup)
211
+ img_label.pack(pady=10)
212
+
213
+ def animate_gif(frame_index=0):
214
+ if frames:
215
+ img_label.config(image=frames[frame_index])
216
+ popup.after(100, animate_gif, (frame_index + 1) % len(frames))
217
+
218
+ animate_gif()
219
+
220
+ except Exception:
221
+ # If gif loading fails, show text instead
222
+ Label(
223
+ popup,
224
+ text=self.language_manager.get("op_compression_info", "Compression Info")
225
+ if self.language_manager
226
+ else "Compression Info",
227
+ font=(CommonElements.FONT, 16, "bold"),
228
+ ).pack(pady=10)
229
+ self.logger.error("Error loading compression error GIF", exc_info=True)
230
+ else:
231
+ # If gif file doesn't exist, show icon
232
+ Label(
233
+ popup,
234
+ text=self.language_manager.get("op_compression_info", "Compression Info")
235
+ if self.language_manager
236
+ else "Compression Info",
237
+ font=(CommonElements.FONT, 16, "bold"),
238
+ ).pack(pady=10)
239
+
240
+ # Info message with better formatting
241
+ info_text = (
242
+ self.language_manager.get(
243
+ "op_compression_info_msg",
244
+ "Compression completed but no size reduction detected.\nThis file has already been optimized or contains\nelements that cannot be compressed further.\nIf you need further compression, consider using the\n'Microsoft Print to PDF' option from the print dialog.",
245
+ )
246
+ if self.language_manager
247
+ else "Compression completed but no size reduction detected.\nThis file has already been optimized or contains\nelements that cannot be compressed further.\nIf you need further compression, consider using the\n'Microsoft Print to PDF' option from the print dialog."
248
+ )
249
+
250
+ Label(
251
+ popup,
252
+ text=info_text,
253
+ justify="center",
254
+ wraplength=400,
255
+ font=(CommonElements.FONT, 10),
256
+ padx=20,
257
+ pady=10,
258
+ ).pack(pady=10)
259
+
260
+ # OK button
261
+ Button(popup, text="OK", command=popup.destroy, width=10, font=(CommonElements.FONT, 10)).pack(pady=15)
262
+
263
+ # Center the popup on screen
264
+ popup.update_idletasks()
265
+ x = (popup.winfo_screenwidth() // 2) - (popup.winfo_width() // 2)
266
+ y = (popup.winfo_screenheight() // 2) - (popup.winfo_height() // 2)
267
+ popup.geometry(f"+{x}+{y}")
268
+
269
+ except Exception:
270
+ # Fallback to simple messagebox if custom popup fails
271
+ if messagebox:
272
+ messagebox.showinfo(
273
+ self.language_manager.get("op_compression_info", "Compression Info")
274
+ if self.language_manager
275
+ else "Compression Info",
276
+ self.language_manager.get(
277
+ "op_compression_info_msg",
278
+ "Compression completed but no size reduction detected.\nThis file has already been optimized or contains elements that cannot be compressed further.\nIf you need further compression, consider using the 'Microsoft Print to PDF' option from the print dialog.",
279
+ )
280
+ if self.language_manager
281
+ else "Compression completed but no size reduction detected.\nThis file has already been optimized or contains elements that cannot be compressed further.\nIf you need further compression, consider using the 'Microsoft Print to PDF' option from the print dialog.",
282
+ )
@@ -0,0 +1,104 @@
1
+ """
2
+ PDF Merge Module for SafePDF
3
+ Handles PDF merging operations
4
+ """
5
+
6
+ from typing import List, Tuple
7
+
8
+ try:
9
+ from PyPDF2 import PdfReader, PdfWriter
10
+ except ImportError:
11
+ PdfReader = PdfWriter = None
12
+
13
+ from SafePDF.logger.logging_config import get_logger
14
+
15
+
16
+ class PDFMerger:
17
+ """Class handling PDF merge operations"""
18
+
19
+ def __init__(self, progress_callback=None, language_manager=None, atomic_write_file=None):
20
+ """
21
+ Initialize PDF merger
22
+
23
+ Args:
24
+ progress_callback: Function to call for progress updates (0-100)
25
+ language_manager: Language manager for localization
26
+ atomic_write_file: Function for atomic file writing
27
+ """
28
+ self.progress_callback = progress_callback
29
+ self.language_manager = language_manager
30
+ self._atomic_write_file = atomic_write_file
31
+ self._cancel_requested = False
32
+ self.logger = get_logger("SafePDF.PDFMerge")
33
+
34
+ def update_progress(self, value):
35
+ """Update progress if callback is available"""
36
+ if self.progress_callback:
37
+ self.progress_callback(value)
38
+
39
+ def request_cancel(self):
40
+ """Request cancellation of a running operation."""
41
+ self._cancel_requested = True
42
+
43
+ def merge_pdfs(self, input_paths: List[str], output_path: str) -> Tuple[bool, str]:
44
+ """
45
+ Merge multiple PDF files
46
+
47
+ Args:
48
+ input_paths: List of input PDF file paths
49
+ output_path: Output merged PDF file path
50
+
51
+ Returns:
52
+ Tuple of (success, message)
53
+ """
54
+ try:
55
+ if not PdfReader or not PdfWriter:
56
+ return False, (
57
+ self.language_manager.get("op_pypdf_unavailable", "PyPDF2/pypdf not available")
58
+ if self.language_manager
59
+ else "PyPDF2/pypdf not available"
60
+ )
61
+
62
+ self.update_progress(10)
63
+
64
+ writer = PdfWriter()
65
+ total_files = len(input_paths)
66
+
67
+ for i, input_path in enumerate(input_paths):
68
+ if self._cancel_requested:
69
+ return False, (
70
+ self.language_manager.get("op_cancelled", "Operation cancelled by user")
71
+ if self.language_manager
72
+ else "Operation cancelled by user"
73
+ )
74
+ with open(input_path, "rb") as input_file:
75
+ reader = PdfReader(input_file)
76
+ for page in reader.pages:
77
+ writer.add_page(page)
78
+
79
+ self.update_progress(10 + (80 * i // total_files))
80
+
81
+ def _write_merged(tmpf):
82
+ writer.write(tmpf)
83
+
84
+ if self._atomic_write_file:
85
+ self._atomic_write_file(output_path, _write_merged)
86
+ else:
87
+ with open(output_path, "wb") as f:
88
+ _write_merged(f)
89
+
90
+ self.update_progress(100)
91
+ success_msg = (
92
+ self.language_manager.get("op_merge_success", "Successfully merged {total_files} PDF files")
93
+ if self.language_manager
94
+ else "Successfully merged {total_files} PDF files"
95
+ )
96
+ return True, success_msg.format(total_files=total_files)
97
+
98
+ except Exception as e:
99
+ error_msg = (
100
+ self.language_manager.get("op_merge_failed", "Merge failed: {error}")
101
+ if self.language_manager
102
+ else "Merge failed: {error}"
103
+ )
104
+ return False, error_msg.format(error=str(e))