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.
- SafePDF/__init__.py +10 -0
- SafePDF/ctrl/__init__.py +0 -0
- SafePDF/ctrl/language_manager.py +69 -0
- SafePDF/ctrl/safe_pdf_controller.py +469 -0
- SafePDF/logger/__init__.py +0 -0
- SafePDF/logger/logging_config.py +94 -0
- SafePDF/ops/__init__.py +0 -0
- SafePDF/ops/license_manager.py +247 -0
- SafePDF/ops/pdf2docx.py +157 -0
- SafePDF/ops/pdf2jpeg.py +116 -0
- SafePDF/ops/pdf_compress.py +282 -0
- SafePDF/ops/pdf_merge.py +104 -0
- SafePDF/ops/pdf_operations.py +563 -0
- SafePDF/ops/pdf_rotate.py +102 -0
- SafePDF/ops/pdf_split.py +178 -0
- SafePDF/ops/updates.py +308 -0
- SafePDF/safe_pdf_app.py +121 -0
- SafePDF/test/__init__.py +0 -0
- SafePDF/test/test_compression.py +79 -0
- SafePDF/test/test_pro_dialog.py +45 -0
- SafePDF/text/de/help_content.txt +58 -0
- SafePDF/text/de/pro_features.txt +9 -0
- SafePDF/text/de/ui.json +260 -0
- SafePDF/text/de/welcome_content.txt +24 -0
- SafePDF/text/en/help_content.txt +42 -0
- SafePDF/text/en/pro_features.txt +8 -0
- SafePDF/text/en/ui.json +260 -0
- SafePDF/text/en/welcome_content.txt +25 -0
- SafePDF/text/tr/help_content.txt +53 -0
- SafePDF/text/tr/pro_features.txt +8 -0
- SafePDF/text/tr/ui.json +260 -0
- SafePDF/text/tr/welcome_content.txt +24 -0
- SafePDF/ui/__init__.py +11 -0
- SafePDF/ui/common_elements.py +40 -0
- SafePDF/ui/help_ui.py +233 -0
- SafePDF/ui/language_elements.py +9 -0
- SafePDF/ui/operation_settings.py +377 -0
- SafePDF/ui/safe_pdf_ui.py +3497 -0
- SafePDF/ui/settings_ui.py +394 -0
- SafePDF/ui/tabs_manager.py +235 -0
- SafePDF/ui/update_ui.py +717 -0
- SafePDF/version.txt +34 -0
- safepdf-1.0.11.dist-info/METADATA +162 -0
- safepdf-1.0.11.dist-info/RECORD +48 -0
- safepdf-1.0.11.dist-info/WHEEL +5 -0
- safepdf-1.0.11.dist-info/entry_points.txt +2 -0
- safepdf-1.0.11.dist-info/licenses/LICENSE +674 -0
- safepdf-1.0.11.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,563 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PDF Operations Backend for SafePDF
|
|
3
|
+
Implements various PDF manipulation operations using PyPDF2/pypdf and Pillow
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import os
|
|
7
|
+
from os import path as os_path
|
|
8
|
+
from tempfile import mkstemp as tmp_mkstemp
|
|
9
|
+
from typing import List, Tuple
|
|
10
|
+
|
|
11
|
+
from SafePDF.logger.logging_config import get_logger
|
|
12
|
+
from SafePDF.ops.pdf2docx import PDFToWordConverter
|
|
13
|
+
from SafePDF.ops.pdf2jpeg import PDFToJPEGConverter
|
|
14
|
+
from SafePDF.ops.pdf_compress import PDFCompressor
|
|
15
|
+
from SafePDF.ops.pdf_merge import PDFMerger
|
|
16
|
+
from SafePDF.ops.pdf_rotate import PDFRotator
|
|
17
|
+
from SafePDF.ops.pdf_split import PDFSplitter
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
import tkinter as tk
|
|
21
|
+
from tkinter import Button, Label, Toplevel, messagebox
|
|
22
|
+
except ImportError:
|
|
23
|
+
messagebox = Toplevel = Label = Button = tk = None
|
|
24
|
+
|
|
25
|
+
try:
|
|
26
|
+
from PyPDF2 import PdfReader, PdfWriter
|
|
27
|
+
from PyPDF2.errors import PdfReadError
|
|
28
|
+
except ImportError:
|
|
29
|
+
print("Warning: PyPDF2 not installed. PDF operations will not work.")
|
|
30
|
+
PdfReader = PdfWriter = None
|
|
31
|
+
|
|
32
|
+
try:
|
|
33
|
+
from PIL import Image, ImageTk
|
|
34
|
+
except ImportError:
|
|
35
|
+
print("Warning: PIL/Pillow not installed. Some operations may not work.")
|
|
36
|
+
Image = ImageTk = None
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
import pypdfium2 as pdfium
|
|
40
|
+
except ImportError:
|
|
41
|
+
print("Warning: pypdfium2 not installed. PDF to image conversion will not work.")
|
|
42
|
+
pdfium = None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class PDFOperations:
|
|
46
|
+
"""Class containing all PDF manipulation operations"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, progress_callback=None, language_manager=None):
|
|
49
|
+
"""
|
|
50
|
+
Initialize PDF operations handler
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
progress_callback: Function to call for progress updates (0-100)
|
|
54
|
+
language_manager: Language manager for localization
|
|
55
|
+
"""
|
|
56
|
+
self.progress_callback = progress_callback
|
|
57
|
+
self.language_manager = language_manager
|
|
58
|
+
# Cancellation flag that can be set by controller/UI
|
|
59
|
+
self._cancel_requested = False
|
|
60
|
+
|
|
61
|
+
# Module logger
|
|
62
|
+
self.logger = get_logger("SafePDF.PDFOps")
|
|
63
|
+
|
|
64
|
+
# Initialize PDF compressor with shared dependencies
|
|
65
|
+
self.compressor = PDFCompressor(
|
|
66
|
+
progress_callback=self.update_progress,
|
|
67
|
+
language_manager=self.language_manager,
|
|
68
|
+
atomic_write_file=self._atomic_write_file,
|
|
69
|
+
validate_pdf=self.validate_pdf,
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
# Initialize PDF to JPEG converter
|
|
73
|
+
self.jpeg_converter = PDFToJPEGConverter(
|
|
74
|
+
progress_callback=self.update_progress, language_manager=self.language_manager
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
# Initialize PDF to Word converter
|
|
78
|
+
self.word_converter = PDFToWordConverter(
|
|
79
|
+
progress_callback=self.update_progress,
|
|
80
|
+
language_manager=self.language_manager,
|
|
81
|
+
atomic_write_via_path=self._atomic_write_via_path,
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
# Initialize PDF splitter
|
|
85
|
+
self.splitter = PDFSplitter(
|
|
86
|
+
progress_callback=self.update_progress,
|
|
87
|
+
language_manager=self.language_manager,
|
|
88
|
+
atomic_write_file=self._atomic_write_file,
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
# Initialize PDF merger
|
|
92
|
+
self.merger = PDFMerger(
|
|
93
|
+
progress_callback=self.update_progress,
|
|
94
|
+
language_manager=self.language_manager,
|
|
95
|
+
atomic_write_file=self._atomic_write_file,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# Initialize PDF rotator
|
|
99
|
+
self.rotator = PDFRotator(
|
|
100
|
+
progress_callback=self.update_progress,
|
|
101
|
+
language_manager=self.language_manager,
|
|
102
|
+
atomic_write_file=self._atomic_write_file,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
def _ensure_parent_dir(self, file_path: str):
|
|
106
|
+
"""
|
|
107
|
+
Ensure the parent directory for `file_path` exists. If `file_path`
|
|
108
|
+
does not contain a directory component, do nothing.
|
|
109
|
+
"""
|
|
110
|
+
try:
|
|
111
|
+
parent = os_path.dirname(file_path) if file_path else ""
|
|
112
|
+
if parent:
|
|
113
|
+
os.makedirs(parent, exist_ok=True)
|
|
114
|
+
except Exception:
|
|
115
|
+
# Creation failure should be handled by the caller when opening/writing files.
|
|
116
|
+
self.logger.error(f"Failed to create parent directory for {file_path}", exc_info=True)
|
|
117
|
+
pass
|
|
118
|
+
|
|
119
|
+
def _atomic_write_file(self, final_path: str, write_func):
|
|
120
|
+
"""
|
|
121
|
+
Atomically write to `final_path` using a temp file in the same directory.
|
|
122
|
+
`write_func` is called with an open file object (binary mode) to write content.
|
|
123
|
+
Uses os.replace for atomic move and ensures cleanup on errors.
|
|
124
|
+
"""
|
|
125
|
+
parent = os_path.dirname(final_path) or os.getcwd()
|
|
126
|
+
self._ensure_parent_dir(final_path)
|
|
127
|
+
|
|
128
|
+
fd = None
|
|
129
|
+
tmp_path = None
|
|
130
|
+
try:
|
|
131
|
+
# Create secure temp file in same directory as target
|
|
132
|
+
fd, tmp_path = tmp_mkstemp(
|
|
133
|
+
prefix=".safepdf_tmp_", suffix=os_path.splitext(final_path)[1] or ".tmp", dir=parent
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
# Write content via callback
|
|
137
|
+
with os.fdopen(fd, "wb") as tmpf:
|
|
138
|
+
fd = None # fdopen takes ownership
|
|
139
|
+
write_func(tmpf)
|
|
140
|
+
tmpf.flush()
|
|
141
|
+
try:
|
|
142
|
+
os.fsync(tmpf.fileno())
|
|
143
|
+
except (OSError, AttributeError):
|
|
144
|
+
pass
|
|
145
|
+
|
|
146
|
+
# Atomic replace
|
|
147
|
+
os.replace(tmp_path, final_path)
|
|
148
|
+
tmp_path = None # Successfully moved
|
|
149
|
+
|
|
150
|
+
except Exception:
|
|
151
|
+
self.logger.error(f"Error during atomic write to {final_path}", exc_info=True)
|
|
152
|
+
raise
|
|
153
|
+
finally:
|
|
154
|
+
# Cleanup on error
|
|
155
|
+
if fd is not None:
|
|
156
|
+
try:
|
|
157
|
+
os.close(fd)
|
|
158
|
+
except Exception:
|
|
159
|
+
self.logger.error("Error closing file descriptor", exc_info=True)
|
|
160
|
+
pass
|
|
161
|
+
if tmp_path and os_path.exists(tmp_path):
|
|
162
|
+
try:
|
|
163
|
+
os.remove(tmp_path)
|
|
164
|
+
except Exception:
|
|
165
|
+
self.logger.error("Error removing temporary file", exc_info=True)
|
|
166
|
+
pass
|
|
167
|
+
|
|
168
|
+
def _atomic_write_via_path(self, final_path: str, write_path_func):
|
|
169
|
+
"""
|
|
170
|
+
Atomically write to `final_path` by providing a temp path to write_path_func.
|
|
171
|
+
`write_path_func` is called with a temp file path (string) to write to.
|
|
172
|
+
Uses os.replace for atomic move and ensures cleanup on errors.
|
|
173
|
+
"""
|
|
174
|
+
parent = os_path.dirname(final_path) or os.getcwd()
|
|
175
|
+
self._ensure_parent_dir(final_path)
|
|
176
|
+
|
|
177
|
+
fd = None
|
|
178
|
+
tmp_path = None
|
|
179
|
+
try:
|
|
180
|
+
# Create secure temp file in same directory
|
|
181
|
+
fd, tmp_path = tmp_mkstemp(
|
|
182
|
+
prefix=".safepdf_tmp_", suffix=os_path.splitext(final_path)[1] or ".tmp", dir=parent
|
|
183
|
+
)
|
|
184
|
+
os.close(fd)
|
|
185
|
+
fd = None
|
|
186
|
+
|
|
187
|
+
# Let caller write to temp path
|
|
188
|
+
write_path_func(tmp_path)
|
|
189
|
+
|
|
190
|
+
# Atomic replace
|
|
191
|
+
os.replace(tmp_path, final_path)
|
|
192
|
+
tmp_path = None # Successfully moved
|
|
193
|
+
|
|
194
|
+
except Exception:
|
|
195
|
+
raise
|
|
196
|
+
finally:
|
|
197
|
+
# Cleanup on error
|
|
198
|
+
if fd is not None:
|
|
199
|
+
try:
|
|
200
|
+
os.close(fd)
|
|
201
|
+
except Exception:
|
|
202
|
+
pass
|
|
203
|
+
if tmp_path and os_path.exists(tmp_path):
|
|
204
|
+
try:
|
|
205
|
+
os.remove(tmp_path)
|
|
206
|
+
except Exception:
|
|
207
|
+
pass
|
|
208
|
+
|
|
209
|
+
def update_progress(self, value):
|
|
210
|
+
"""Update progress if callback is available"""
|
|
211
|
+
if self.progress_callback:
|
|
212
|
+
self.progress_callback(value)
|
|
213
|
+
|
|
214
|
+
def request_cancel(self):
|
|
215
|
+
"""Request cancellation of a running operation."""
|
|
216
|
+
self._cancel_requested = True
|
|
217
|
+
|
|
218
|
+
def validate_pdf(self, file_path: str) -> bool:
|
|
219
|
+
"""
|
|
220
|
+
Validate if file is a valid PDF
|
|
221
|
+
|
|
222
|
+
Args:
|
|
223
|
+
file_path: Path to PDF file
|
|
224
|
+
|
|
225
|
+
Returns:
|
|
226
|
+
True if valid PDF, False otherwise
|
|
227
|
+
"""
|
|
228
|
+
try:
|
|
229
|
+
if not PdfReader:
|
|
230
|
+
return False
|
|
231
|
+
|
|
232
|
+
with open(file_path, "rb") as file:
|
|
233
|
+
reader = PdfReader(file)
|
|
234
|
+
# Try to access pages to ensure it's readable
|
|
235
|
+
len(reader.pages)
|
|
236
|
+
return True
|
|
237
|
+
except (PdfReadError, Exception):
|
|
238
|
+
return False
|
|
239
|
+
|
|
240
|
+
def compress_pdf(self, input_path: str, output_path: str, quality: str = "medium") -> Tuple[bool, str]:
|
|
241
|
+
"""
|
|
242
|
+
Compress PDF file (delegates to PDFCompressor)
|
|
243
|
+
|
|
244
|
+
Args:
|
|
245
|
+
input_path: Input PDF file path
|
|
246
|
+
output_path: Output PDF file path
|
|
247
|
+
quality: Compression quality ("low", "medium", "high")
|
|
248
|
+
|
|
249
|
+
Returns:
|
|
250
|
+
Tuple of (success, message)
|
|
251
|
+
"""
|
|
252
|
+
# Sync cancellation flag
|
|
253
|
+
self.compressor._cancel_requested = self._cancel_requested
|
|
254
|
+
return self.compressor.compress_pdf(input_path, output_path, quality)
|
|
255
|
+
|
|
256
|
+
def split_pdf(
|
|
257
|
+
self, input_path: str, output_dir: str, method: str = "pages", page_range: str = None
|
|
258
|
+
) -> Tuple[bool, str]:
|
|
259
|
+
"""
|
|
260
|
+
Split PDF into multiple files (delegates to PDFSplitter)
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
input_path: Input PDF file path
|
|
264
|
+
output_dir: Directory to save split files
|
|
265
|
+
method: Split method ("pages" for each page, "range" for specific range)
|
|
266
|
+
page_range: Page range if method is "range" (e.g., "1-5,7,10-12")
|
|
267
|
+
|
|
268
|
+
Returns:
|
|
269
|
+
Tuple of (success, message)
|
|
270
|
+
"""
|
|
271
|
+
# Sync cancellation flag
|
|
272
|
+
self.splitter._cancel_requested = self._cancel_requested
|
|
273
|
+
return self.splitter.split_pdf(input_path, output_dir, method, page_range)
|
|
274
|
+
|
|
275
|
+
def merge_pdfs(self, input_paths: List[str], output_path: str) -> Tuple[bool, str]:
|
|
276
|
+
"""
|
|
277
|
+
Merge multiple PDF files (delegates to PDFMerger)
|
|
278
|
+
|
|
279
|
+
Args:
|
|
280
|
+
input_paths: List of input PDF file paths
|
|
281
|
+
output_path: Output merged PDF file path
|
|
282
|
+
|
|
283
|
+
Returns:
|
|
284
|
+
Tuple of (success, message)
|
|
285
|
+
"""
|
|
286
|
+
# Sync cancellation flag
|
|
287
|
+
self.merger._cancel_requested = self._cancel_requested
|
|
288
|
+
return self.merger.merge_pdfs(input_paths, output_path)
|
|
289
|
+
|
|
290
|
+
def pdf_to_jpg(self, input_path: str, output_dir: str, dpi: int = 200) -> Tuple[bool, str]:
|
|
291
|
+
"""
|
|
292
|
+
Convert PDF pages to JPG images (delegates to PDFToJPEGConverter)
|
|
293
|
+
|
|
294
|
+
Args:
|
|
295
|
+
input_path: Input PDF file path
|
|
296
|
+
output_dir: Directory to save JPG files
|
|
297
|
+
dpi: Resolution for images (scale factor)
|
|
298
|
+
|
|
299
|
+
Returns:
|
|
300
|
+
Tuple of (success, message)
|
|
301
|
+
"""
|
|
302
|
+
# Sync cancellation flag
|
|
303
|
+
self.jpeg_converter._cancel_requested = self._cancel_requested
|
|
304
|
+
return self.jpeg_converter.pdf_to_jpg(input_path, output_dir, dpi)
|
|
305
|
+
|
|
306
|
+
def rotate_pdf(self, input_path: str, output_path: str, angle: int = 90) -> Tuple[bool, str]:
|
|
307
|
+
"""
|
|
308
|
+
Rotate PDF pages (delegates to PDFRotator)
|
|
309
|
+
|
|
310
|
+
Args:
|
|
311
|
+
input_path: Input PDF file path
|
|
312
|
+
output_path: Output PDF file path
|
|
313
|
+
angle: Rotation angle (90, 180, 270)
|
|
314
|
+
|
|
315
|
+
Returns:
|
|
316
|
+
Tuple of (success, message)
|
|
317
|
+
"""
|
|
318
|
+
# Sync cancellation flag
|
|
319
|
+
self.rotator._cancel_requested = self._cancel_requested
|
|
320
|
+
return self.rotator.rotate_pdf(input_path, output_path, angle)
|
|
321
|
+
|
|
322
|
+
def repair_pdf(self, input_path: str, output_path: str) -> Tuple[bool, str]:
|
|
323
|
+
"""
|
|
324
|
+
Attempt to repair a corrupted PDF
|
|
325
|
+
|
|
326
|
+
Args:
|
|
327
|
+
input_path: Input PDF file path
|
|
328
|
+
output_path: Output repaired PDF file path
|
|
329
|
+
|
|
330
|
+
Returns:
|
|
331
|
+
Tuple of (success, message)
|
|
332
|
+
"""
|
|
333
|
+
try:
|
|
334
|
+
if not PdfReader or not PdfWriter:
|
|
335
|
+
return False, self.language_manager.get(
|
|
336
|
+
"op_pypdf_unavailable", "PyPDF2/pypdf not available"
|
|
337
|
+
) if self.language_manager else "PyPDF2/pypdf not available"
|
|
338
|
+
|
|
339
|
+
self.update_progress(10)
|
|
340
|
+
|
|
341
|
+
with open(input_path, "rb") as input_file:
|
|
342
|
+
reader = PdfReader(input_file, strict=False) # Less strict parsing
|
|
343
|
+
writer = PdfWriter()
|
|
344
|
+
|
|
345
|
+
self.update_progress(30)
|
|
346
|
+
|
|
347
|
+
pages_recovered = 0
|
|
348
|
+
total_pages = len(reader.pages) if hasattr(reader, "pages") else 0
|
|
349
|
+
|
|
350
|
+
try:
|
|
351
|
+
for i, page in enumerate(reader.pages):
|
|
352
|
+
if self._cancel_requested:
|
|
353
|
+
return False, self.language_manager.get(
|
|
354
|
+
"op_cancelled", "Operation cancelled by user"
|
|
355
|
+
) if self.language_manager else "Operation cancelled by user"
|
|
356
|
+
try:
|
|
357
|
+
writer.add_page(page)
|
|
358
|
+
pages_recovered += 1
|
|
359
|
+
if total_pages > 0:
|
|
360
|
+
self.update_progress(30 + (60 * i // total_pages))
|
|
361
|
+
except Exception:
|
|
362
|
+
# Skip corrupted pages
|
|
363
|
+
continue
|
|
364
|
+
|
|
365
|
+
except Exception:
|
|
366
|
+
pass # Continue with whatever pages we could recover
|
|
367
|
+
|
|
368
|
+
if pages_recovered > 0:
|
|
369
|
+
|
|
370
|
+
def _write_repaired(tmpf):
|
|
371
|
+
writer.write(tmpf)
|
|
372
|
+
|
|
373
|
+
self._atomic_write_file(output_path, _write_repaired)
|
|
374
|
+
self.update_progress(100)
|
|
375
|
+
success_msg = (
|
|
376
|
+
self.language_manager.get(
|
|
377
|
+
"op_repair_success", "PDF repaired. Recovered {pages_recovered} pages"
|
|
378
|
+
)
|
|
379
|
+
if self.language_manager
|
|
380
|
+
else "PDF repaired. Recovered {pages_recovered} pages"
|
|
381
|
+
)
|
|
382
|
+
return True, success_msg.format(pages_recovered=pages_recovered)
|
|
383
|
+
else:
|
|
384
|
+
return False, self.language_manager.get(
|
|
385
|
+
"op_repair_no_pages", "Could not recover any pages from the PDF"
|
|
386
|
+
) if self.language_manager else "Could not recover any pages from the PDF"
|
|
387
|
+
|
|
388
|
+
except Exception as e:
|
|
389
|
+
error_msg = (
|
|
390
|
+
self.language_manager.get("op_repair_failed", "Repair failed: {error}")
|
|
391
|
+
if self.language_manager
|
|
392
|
+
else "Repair failed: {error}"
|
|
393
|
+
)
|
|
394
|
+
return False, error_msg.format(error=str(e))
|
|
395
|
+
|
|
396
|
+
def get_pdf_info(self, file_path: str) -> dict:
|
|
397
|
+
"""
|
|
398
|
+
Get basic information about a PDF file
|
|
399
|
+
|
|
400
|
+
Args:
|
|
401
|
+
file_path: Path to PDF file
|
|
402
|
+
|
|
403
|
+
Returns:
|
|
404
|
+
Dictionary with PDF information
|
|
405
|
+
"""
|
|
406
|
+
try:
|
|
407
|
+
if not PdfReader:
|
|
408
|
+
return {"error": "PyPDF2/pypdf not available"}
|
|
409
|
+
|
|
410
|
+
with open(file_path, "rb") as file:
|
|
411
|
+
reader = PdfReader(file)
|
|
412
|
+
|
|
413
|
+
info = {
|
|
414
|
+
"pages": len(reader.pages),
|
|
415
|
+
"file_size": os_path.getsize(file_path),
|
|
416
|
+
"file_name": os_path.basename(file_path),
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
if reader.metadata:
|
|
420
|
+
info.update(
|
|
421
|
+
{
|
|
422
|
+
"title": reader.metadata.get("/Title", "Unknown"),
|
|
423
|
+
"author": reader.metadata.get("/Author", "Unknown"),
|
|
424
|
+
"creator": reader.metadata.get("/Creator", "Unknown"),
|
|
425
|
+
"producer": reader.metadata.get("/Producer", "Unknown"),
|
|
426
|
+
}
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
return info
|
|
430
|
+
|
|
431
|
+
except Exception as e:
|
|
432
|
+
return {"error": str(e)}
|
|
433
|
+
|
|
434
|
+
def pdf_to_txt(self, input_path: str, output_path: str) -> Tuple[bool, str]:
|
|
435
|
+
"""
|
|
436
|
+
Extract text from PDF and save to TXT file
|
|
437
|
+
|
|
438
|
+
Args:
|
|
439
|
+
input_path: Path to input PDF file
|
|
440
|
+
output_path: Path to output TXT file
|
|
441
|
+
|
|
442
|
+
Returns:
|
|
443
|
+
Tuple of (success: bool, message: str)
|
|
444
|
+
"""
|
|
445
|
+
try:
|
|
446
|
+
if not PdfReader:
|
|
447
|
+
return False, self.language_manager.get(
|
|
448
|
+
"op_pypdf_unavailable", "PyPDF2/pypdf not available"
|
|
449
|
+
) if self.language_manager else "PyPDF2/pypdf not available"
|
|
450
|
+
|
|
451
|
+
with open(input_path, "rb") as file:
|
|
452
|
+
reader = PdfReader(file)
|
|
453
|
+
text_content = ""
|
|
454
|
+
|
|
455
|
+
total_pages = len(reader.pages)
|
|
456
|
+
for i, page in enumerate(reader.pages):
|
|
457
|
+
self.update_progress(int((i + 1) / total_pages * 100))
|
|
458
|
+
if self._cancel_requested:
|
|
459
|
+
return False, self.language_manager.get(
|
|
460
|
+
"op_word_cancelled", "Operation cancelled"
|
|
461
|
+
) if self.language_manager else "Operation cancelled"
|
|
462
|
+
|
|
463
|
+
text_content += page.extract_text() + "\n\n"
|
|
464
|
+
|
|
465
|
+
def _write_text(tmpf):
|
|
466
|
+
tmpf.write(text_content.encode("utf-8"))
|
|
467
|
+
|
|
468
|
+
self._atomic_write_file(output_path, _write_text)
|
|
469
|
+
success_msg = (
|
|
470
|
+
self.language_manager.get("op_text_success", "Text extracted to {output_path}")
|
|
471
|
+
if self.language_manager
|
|
472
|
+
else "Text extracted to {output_path}"
|
|
473
|
+
)
|
|
474
|
+
return True, success_msg.format(output_path=output_path)
|
|
475
|
+
|
|
476
|
+
except Exception as e:
|
|
477
|
+
error_msg = (
|
|
478
|
+
self.language_manager.get("op_text_failed", "Text extraction failed: {error}")
|
|
479
|
+
if self.language_manager
|
|
480
|
+
else "Text extraction failed: {error}"
|
|
481
|
+
)
|
|
482
|
+
return False, error_msg.format(error=str(e))
|
|
483
|
+
|
|
484
|
+
def extract_hidden_info(self, input_path: str, output_path: str) -> Tuple[bool, str]:
|
|
485
|
+
"""
|
|
486
|
+
Extract hidden information and metadata from PDF
|
|
487
|
+
|
|
488
|
+
Args:
|
|
489
|
+
input_path: Path to input PDF file
|
|
490
|
+
output_path: Path to output TXT file with extracted info
|
|
491
|
+
|
|
492
|
+
Returns:
|
|
493
|
+
Tuple of (success: bool, message: str)
|
|
494
|
+
"""
|
|
495
|
+
try:
|
|
496
|
+
if not PdfReader:
|
|
497
|
+
return False, self.language_manager.get(
|
|
498
|
+
"op_pypdf_unavailable", "PyPDF2/pypdf not available"
|
|
499
|
+
) if self.language_manager else "PyPDF2/pypdf not available"
|
|
500
|
+
|
|
501
|
+
info = self.get_pdf_info(input_path)
|
|
502
|
+
if "error" in info:
|
|
503
|
+
return False, info["error"]
|
|
504
|
+
|
|
505
|
+
# Extract additional hidden information
|
|
506
|
+
hidden_info = []
|
|
507
|
+
hidden_info.append("=== PDF METADATA ===")
|
|
508
|
+
hidden_info.append(f"Title: {info.get('title', 'N/A')}")
|
|
509
|
+
hidden_info.append(f"Author: {info.get('author', 'N/A')}")
|
|
510
|
+
hidden_info.append(f"Creator: {info.get('creator', 'N/A')}")
|
|
511
|
+
hidden_info.append(f"Producer: {info.get('producer', 'N/A')}")
|
|
512
|
+
hidden_info.append(f"Pages: {info.get('pages', 'N/A')}")
|
|
513
|
+
hidden_info.append(f"File Size: {info.get('file_size', 'N/A')} bytes")
|
|
514
|
+
|
|
515
|
+
# Try to extract more detailed info
|
|
516
|
+
try:
|
|
517
|
+
with open(input_path, "rb") as file:
|
|
518
|
+
reader = PdfReader(file)
|
|
519
|
+
if reader.trailer and "/Info" in reader.trailer:
|
|
520
|
+
info_dict = reader.trailer["/Info"]
|
|
521
|
+
hidden_info.append("\n=== ADDITIONAL INFO DICTIONARY ===")
|
|
522
|
+
for key, value in info_dict.items():
|
|
523
|
+
hidden_info.append(f"{key}: {value}")
|
|
524
|
+
except Exception as e:
|
|
525
|
+
hidden_info.append(f"\nError extracting additional info: {str(e)}")
|
|
526
|
+
|
|
527
|
+
hidden_info.append("\n=== END OF EXTRACTED INFORMATION ===")
|
|
528
|
+
hidden_info.append("These details are extracted by SafePDF.")
|
|
529
|
+
|
|
530
|
+
# Write to output file atomically
|
|
531
|
+
def _write_info(tmpf):
|
|
532
|
+
tmpf.write("\n".join(hidden_info).encode("utf-8"))
|
|
533
|
+
|
|
534
|
+
self._atomic_write_file(output_path, _write_info)
|
|
535
|
+
success_msg = (
|
|
536
|
+
self.language_manager.get("op_hidden_success", "Hidden information extracted to {output_path}")
|
|
537
|
+
if self.language_manager
|
|
538
|
+
else "Hidden information extracted to {output_path}"
|
|
539
|
+
)
|
|
540
|
+
return True, success_msg.format(output_path=output_path)
|
|
541
|
+
|
|
542
|
+
except Exception as e:
|
|
543
|
+
error_msg = (
|
|
544
|
+
self.language_manager.get("op_hidden_failed", "Hidden info extraction failed: {error}")
|
|
545
|
+
if self.language_manager
|
|
546
|
+
else "Hidden info extraction failed: {error}"
|
|
547
|
+
)
|
|
548
|
+
return False, error_msg.format(error=str(e))
|
|
549
|
+
|
|
550
|
+
def pdf_to_word(self, input_path: str, output_path: str) -> Tuple[bool, str]:
|
|
551
|
+
"""
|
|
552
|
+
Convert PDF to Word document (delegates to PDFToWordConverter)
|
|
553
|
+
|
|
554
|
+
Args:
|
|
555
|
+
input_path: Path to input PDF file
|
|
556
|
+
output_path: Path to output DOCX file
|
|
557
|
+
|
|
558
|
+
Returns:
|
|
559
|
+
Tuple of (success: bool, message: str)
|
|
560
|
+
"""
|
|
561
|
+
# Sync cancellation flag
|
|
562
|
+
self.word_converter._cancel_requested = self._cancel_requested
|
|
563
|
+
return self.word_converter.pdf_to_word(input_path, output_path)
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PDF Rotate Module for SafePDF
|
|
3
|
+
Handles PDF rotation operations
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from typing import 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 PDFRotator:
|
|
17
|
+
"""Class handling PDF rotation operations"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, progress_callback=None, language_manager=None, atomic_write_file=None):
|
|
20
|
+
"""
|
|
21
|
+
Initialize PDF rotator
|
|
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.PDFRotate")
|
|
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 rotate_pdf(self, input_path: str, output_path: str, angle: int = 90) -> Tuple[bool, str]:
|
|
44
|
+
"""
|
|
45
|
+
Rotate PDF pages
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
input_path: Input PDF file path
|
|
49
|
+
output_path: Output PDF file path
|
|
50
|
+
angle: Rotation angle (90, 180, 270)
|
|
51
|
+
|
|
52
|
+
Returns:
|
|
53
|
+
Tuple of (success, message)
|
|
54
|
+
"""
|
|
55
|
+
try:
|
|
56
|
+
if not PdfReader or not PdfWriter:
|
|
57
|
+
return False, self.language_manager.get(
|
|
58
|
+
"op_pypdf_unavailable", "PyPDF2/pypdf not available"
|
|
59
|
+
) if self.language_manager else "PyPDF2/pypdf not available"
|
|
60
|
+
|
|
61
|
+
self.update_progress(10)
|
|
62
|
+
|
|
63
|
+
with open(input_path, "rb") as input_file:
|
|
64
|
+
reader = PdfReader(input_file)
|
|
65
|
+
writer = PdfWriter()
|
|
66
|
+
|
|
67
|
+
total_pages = len(reader.pages)
|
|
68
|
+
self.update_progress(30)
|
|
69
|
+
|
|
70
|
+
for i, page in enumerate(reader.pages):
|
|
71
|
+
if self._cancel_requested:
|
|
72
|
+
return False, self.language_manager.get(
|
|
73
|
+
"op_cancelled", "Operation cancelled by user"
|
|
74
|
+
) if self.language_manager else "Operation cancelled by user"
|
|
75
|
+
rotated_page = page.rotate(angle)
|
|
76
|
+
writer.add_page(rotated_page)
|
|
77
|
+
self.update_progress(30 + (60 * i // total_pages))
|
|
78
|
+
|
|
79
|
+
def _write_rotated(tmpf):
|
|
80
|
+
writer.write(tmpf)
|
|
81
|
+
|
|
82
|
+
if self._atomic_write_file:
|
|
83
|
+
self._atomic_write_file(output_path, _write_rotated)
|
|
84
|
+
else:
|
|
85
|
+
with open(output_path, "wb") as f:
|
|
86
|
+
_write_rotated(f)
|
|
87
|
+
|
|
88
|
+
self.update_progress(100)
|
|
89
|
+
success_msg = (
|
|
90
|
+
self.language_manager.get("op_rotate_success", "PDF rotated by {angle} degrees")
|
|
91
|
+
if self.language_manager
|
|
92
|
+
else "PDF rotated by {angle} degrees"
|
|
93
|
+
)
|
|
94
|
+
return True, success_msg.format(angle=angle)
|
|
95
|
+
|
|
96
|
+
except Exception as e:
|
|
97
|
+
error_msg = (
|
|
98
|
+
self.language_manager.get("op_rotate_failed", "Rotation failed: {error}")
|
|
99
|
+
if self.language_manager
|
|
100
|
+
else "Rotation failed: {error}"
|
|
101
|
+
)
|
|
102
|
+
return False, error_msg.format(error=str(e))
|