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,247 @@
|
|
|
1
|
+
"""
|
|
2
|
+
License Manager - Handles license verification and validation
|
|
3
|
+
by mcagriaksoy - 2025
|
|
4
|
+
|
|
5
|
+
This module manages license file verification using RSA signatures,
|
|
6
|
+
expiry date validation, and pro feature activation.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import base64
|
|
10
|
+
import json
|
|
11
|
+
from datetime import datetime
|
|
12
|
+
from os import path as os_path
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
try:
|
|
16
|
+
from Crypto.Hash import SHA256
|
|
17
|
+
from Crypto.PublicKey import RSA
|
|
18
|
+
from Crypto.Signature import pkcs1_15
|
|
19
|
+
except ImportError:
|
|
20
|
+
# Graceful fallback if pycryptodome is not installed
|
|
21
|
+
RSA = None
|
|
22
|
+
pkcs1_15 = None
|
|
23
|
+
SHA256 = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class LicenseManager:
|
|
27
|
+
"""Manages license file verification and validation"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, logger=None, public_key_path=None):
|
|
30
|
+
"""
|
|
31
|
+
Initialize License Manager
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
logger: Logger instance for debugging
|
|
35
|
+
public_key_path: Path to the public.pem key file.
|
|
36
|
+
If None, will look in SafePDF/keys/public.pem
|
|
37
|
+
"""
|
|
38
|
+
self.logger = logger
|
|
39
|
+
self.public_key = None
|
|
40
|
+
self.public_key_path = public_key_path or self._get_default_public_key_path()
|
|
41
|
+
|
|
42
|
+
# Load public key
|
|
43
|
+
self._load_public_key()
|
|
44
|
+
|
|
45
|
+
def _get_default_public_key_path(self):
|
|
46
|
+
"""Get the default public key path from the SafePDF keys directory"""
|
|
47
|
+
try:
|
|
48
|
+
# Try to find public.pem in SafePDF/keys/
|
|
49
|
+
current_dir = Path(__file__).parent.parent # SafePDF directory
|
|
50
|
+
public_key_path = current_dir / "keys" / "public.pem"
|
|
51
|
+
|
|
52
|
+
if public_key_path.exists():
|
|
53
|
+
return str(public_key_path)
|
|
54
|
+
except Exception:
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
return None
|
|
58
|
+
|
|
59
|
+
def _load_public_key(self):
|
|
60
|
+
"""Load the public key from file"""
|
|
61
|
+
if not self.public_key_path:
|
|
62
|
+
if self.logger:
|
|
63
|
+
self.logger.error("Public key path not found. License verification disabled.")
|
|
64
|
+
return False
|
|
65
|
+
|
|
66
|
+
try:
|
|
67
|
+
if not os_path.exists(self.public_key_path):
|
|
68
|
+
if self.logger:
|
|
69
|
+
self.logger.error(f"Public key file not found: {self.public_key_path}")
|
|
70
|
+
return False
|
|
71
|
+
|
|
72
|
+
with open(self.public_key_path, "r") as f:
|
|
73
|
+
key_data = f.read()
|
|
74
|
+
|
|
75
|
+
# Import the public key
|
|
76
|
+
if RSA is None:
|
|
77
|
+
if self.logger:
|
|
78
|
+
self.logger.error("pycryptodome is not installed. License verification disabled.")
|
|
79
|
+
return False
|
|
80
|
+
|
|
81
|
+
self.public_key = RSA.import_key(key_data)
|
|
82
|
+
if self.logger:
|
|
83
|
+
self.logger.debug(f"Public key loaded successfully from {self.public_key_path}")
|
|
84
|
+
return True
|
|
85
|
+
|
|
86
|
+
except Exception as e:
|
|
87
|
+
if self.logger:
|
|
88
|
+
self.logger.error(f"Failed to load public key: {e}")
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
def verify_license(self, license_file_path):
|
|
92
|
+
"""
|
|
93
|
+
Verify a license file completely
|
|
94
|
+
|
|
95
|
+
Args:
|
|
96
|
+
license_file_path: Path to the .lic license file
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
Tuple (success: bool, message: str, license_data: dict or None)
|
|
100
|
+
- success: True if license is valid and not expired
|
|
101
|
+
- message: Human-readable status message
|
|
102
|
+
- license_data: Parsed license data if valid, None otherwise
|
|
103
|
+
"""
|
|
104
|
+
if not license_file_path:
|
|
105
|
+
return False, "License file path not provided.", None
|
|
106
|
+
|
|
107
|
+
# Check if file exists
|
|
108
|
+
if not os_path.exists(license_file_path):
|
|
109
|
+
return False, f"License file not found: {license_file_path}", None
|
|
110
|
+
|
|
111
|
+
# Check file extension
|
|
112
|
+
_, ext = os_path.splitext(license_file_path)
|
|
113
|
+
if ext.lower() != ".lic":
|
|
114
|
+
return False, "Invalid license file extension. Expected .lic", None
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
# Read license file
|
|
118
|
+
with open(license_file_path, "r") as f:
|
|
119
|
+
license_json = json.load(f)
|
|
120
|
+
|
|
121
|
+
if self.logger:
|
|
122
|
+
self.logger.debug(f"License file loaded: {license_file_path}")
|
|
123
|
+
|
|
124
|
+
# Extract signature and data
|
|
125
|
+
signature_b64 = license_json.get("signature")
|
|
126
|
+
if not signature_b64:
|
|
127
|
+
return False, "License file missing signature.", None
|
|
128
|
+
|
|
129
|
+
# Create a new dict without signature for verification
|
|
130
|
+
data_for_verification = {k: v for k, v in license_json.items() if k != "signature"}
|
|
131
|
+
|
|
132
|
+
# Verify signature if public key is available
|
|
133
|
+
if self.public_key is None:
|
|
134
|
+
if self.logger:
|
|
135
|
+
self.logger.warning("Public key not available. Signature verification skipped.")
|
|
136
|
+
# Proceed without signature verification
|
|
137
|
+
else:
|
|
138
|
+
signature_valid = self._verify_signature(data_for_verification, signature_b64)
|
|
139
|
+
if not signature_valid:
|
|
140
|
+
return False, "License signature verification failed. License may be tampered.", None
|
|
141
|
+
|
|
142
|
+
# Check expiry date
|
|
143
|
+
if "expires" not in license_json:
|
|
144
|
+
return False, "License file missing expiry date.", None
|
|
145
|
+
|
|
146
|
+
try:
|
|
147
|
+
expiry_date = datetime.strptime(license_json["expires"], "%Y-%m-%d")
|
|
148
|
+
except ValueError:
|
|
149
|
+
return False, "License expiry date format invalid (expected YYYY-MM-DD).", None
|
|
150
|
+
|
|
151
|
+
if datetime.now() > expiry_date:
|
|
152
|
+
days_expired = (datetime.now() - expiry_date).days
|
|
153
|
+
return False, f"License has expired {days_expired} days ago.", None
|
|
154
|
+
|
|
155
|
+
# Check license type
|
|
156
|
+
license_type = license_json.get("type", "pro")
|
|
157
|
+
if license_type not in ["pro", "trial", "basic"]:
|
|
158
|
+
return False, f"Unknown license type: {license_type}", None
|
|
159
|
+
|
|
160
|
+
# All checks passed
|
|
161
|
+
remaining_days = (expiry_date - datetime.now()).days
|
|
162
|
+
message = f"License valid - Type: {license_type}, Remaining days: {remaining_days}"
|
|
163
|
+
|
|
164
|
+
if self.logger:
|
|
165
|
+
self.logger.info(f"✓ License verification successful: {message}")
|
|
166
|
+
|
|
167
|
+
return True, message, license_json
|
|
168
|
+
|
|
169
|
+
except json.JSONDecodeError:
|
|
170
|
+
return False, "License file is not valid JSON.", None
|
|
171
|
+
except Exception as e:
|
|
172
|
+
error_msg = f"Error verifying license: {str(e)}"
|
|
173
|
+
if self.logger:
|
|
174
|
+
self.logger.error(error_msg, exc_info=True)
|
|
175
|
+
return False, error_msg, None
|
|
176
|
+
|
|
177
|
+
def _verify_signature(self, data_dict, signature_b64):
|
|
178
|
+
"""
|
|
179
|
+
Verify the RSA signature of license data
|
|
180
|
+
|
|
181
|
+
Args:
|
|
182
|
+
data_dict: Dictionary of license data (without signature)
|
|
183
|
+
signature_b64: Base64-encoded signature
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
bool: True if signature is valid, False otherwise
|
|
187
|
+
"""
|
|
188
|
+
if self.public_key is None or RSA is None or pkcs1_15 is None or SHA256 is None:
|
|
189
|
+
return False
|
|
190
|
+
|
|
191
|
+
try:
|
|
192
|
+
# Recreate the payload exactly as it was signed
|
|
193
|
+
payload = json.dumps(data_dict, separators=(",", ":")).encode()
|
|
194
|
+
|
|
195
|
+
# Decode the signature
|
|
196
|
+
signature = base64.b64decode(signature_b64)
|
|
197
|
+
|
|
198
|
+
# Verify signature
|
|
199
|
+
h = SHA256.new(payload)
|
|
200
|
+
pkcs1_15.new(self.public_key).verify(h, signature)
|
|
201
|
+
|
|
202
|
+
if self.logger:
|
|
203
|
+
self.logger.debug("Signature verification successful")
|
|
204
|
+
return True
|
|
205
|
+
|
|
206
|
+
except ValueError:
|
|
207
|
+
# Signature verification failed
|
|
208
|
+
if self.logger:
|
|
209
|
+
self.logger.debug("Signature verification failed - signature is invalid")
|
|
210
|
+
return False
|
|
211
|
+
except Exception as e:
|
|
212
|
+
if self.logger:
|
|
213
|
+
self.logger.error(f"Error verifying signature: {e}")
|
|
214
|
+
return False
|
|
215
|
+
|
|
216
|
+
def get_remaining_days(self, license_data):
|
|
217
|
+
"""
|
|
218
|
+
Calculate remaining days from license data
|
|
219
|
+
|
|
220
|
+
Args:
|
|
221
|
+
license_data: Dictionary containing license info with 'expires' key
|
|
222
|
+
|
|
223
|
+
Returns:
|
|
224
|
+
int: Number of remaining days (0 if expired)
|
|
225
|
+
"""
|
|
226
|
+
if not license_data or "expires" not in license_data:
|
|
227
|
+
return 0
|
|
228
|
+
|
|
229
|
+
try:
|
|
230
|
+
expiry_date = datetime.strptime(license_data["expires"], "%Y-%m-%d")
|
|
231
|
+
remaining = (expiry_date - datetime.now()).days
|
|
232
|
+
return max(0, remaining)
|
|
233
|
+
except Exception:
|
|
234
|
+
return 0
|
|
235
|
+
|
|
236
|
+
def is_license_expired(self, license_data):
|
|
237
|
+
"""
|
|
238
|
+
Check if a license is expired
|
|
239
|
+
|
|
240
|
+
Args:
|
|
241
|
+
license_data: Dictionary containing license info with 'expires' key
|
|
242
|
+
|
|
243
|
+
Returns:
|
|
244
|
+
bool: True if expired, False otherwise
|
|
245
|
+
"""
|
|
246
|
+
remaining_days = self.get_remaining_days(license_data)
|
|
247
|
+
return remaining_days == 0 and "expires" in license_data
|
SafePDF/ops/pdf2docx.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PDF to Word/DOCX Conversion Module for SafePDF
|
|
3
|
+
Handles PDF to Word document conversion operations
|
|
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 Tuple
|
|
10
|
+
|
|
11
|
+
import pypdfium2 as pdfium
|
|
12
|
+
from PIL import Image
|
|
13
|
+
from PyPDF2 import PdfReader
|
|
14
|
+
|
|
15
|
+
from SafePDF.logger.logging_config import get_logger
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class PDFToWordConverter:
|
|
19
|
+
"""Class handling PDF to Word/DOCX conversion operations"""
|
|
20
|
+
|
|
21
|
+
def __init__(self, progress_callback=None, language_manager=None, atomic_write_via_path=None):
|
|
22
|
+
"""
|
|
23
|
+
Initialize PDF to Word converter
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
progress_callback: Function to call for progress updates (0-100)
|
|
27
|
+
language_manager: Language manager for localization
|
|
28
|
+
atomic_write_via_path: Function for atomic file writing via path
|
|
29
|
+
"""
|
|
30
|
+
self.progress_callback = progress_callback
|
|
31
|
+
self.language_manager = language_manager
|
|
32
|
+
self._atomic_write_via_path = atomic_write_via_path
|
|
33
|
+
self._cancel_requested = False
|
|
34
|
+
self.logger = get_logger("SafePDF.PDF2Word")
|
|
35
|
+
|
|
36
|
+
def update_progress(self, value):
|
|
37
|
+
"""Update progress if callback is available"""
|
|
38
|
+
if self.progress_callback:
|
|
39
|
+
self.progress_callback(value)
|
|
40
|
+
|
|
41
|
+
def request_cancel(self):
|
|
42
|
+
"""Request cancellation of a running operation."""
|
|
43
|
+
self._cancel_requested = True
|
|
44
|
+
|
|
45
|
+
def pdf_to_word(self, input_path: str, output_path: str) -> Tuple[bool, str]:
|
|
46
|
+
"""
|
|
47
|
+
Convert PDF to Word document using PyPDF2 for text and pypdfium2 for images
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
input_path: Path to input PDF file
|
|
51
|
+
output_path: Path to output DOCX file
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
Tuple of (success: bool, message: str)
|
|
55
|
+
"""
|
|
56
|
+
try:
|
|
57
|
+
# Try to import python-docx
|
|
58
|
+
try:
|
|
59
|
+
from docx import Document
|
|
60
|
+
from docx.shared import Inches
|
|
61
|
+
except ImportError:
|
|
62
|
+
return (
|
|
63
|
+
False,
|
|
64
|
+
self.language_manager.get(
|
|
65
|
+
"op_docx_unavailable", "python-docx not installed. Please install with: pip install python-docx"
|
|
66
|
+
)
|
|
67
|
+
if self.language_manager
|
|
68
|
+
else "python-docx not installed. Please install with: pip install python-docx",
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
if not PdfReader:
|
|
72
|
+
return False, self.language_manager.get(
|
|
73
|
+
"op_pypdf_unavailable", "PyPDF2/pypdf not available"
|
|
74
|
+
) if self.language_manager else "PyPDF2/pypdf not available"
|
|
75
|
+
|
|
76
|
+
# Open PDF with PyPDF2
|
|
77
|
+
doc = Document()
|
|
78
|
+
|
|
79
|
+
with open(input_path, "rb") as file:
|
|
80
|
+
reader = PdfReader(file)
|
|
81
|
+
total_pages = len(reader.pages)
|
|
82
|
+
|
|
83
|
+
for page_num in range(total_pages):
|
|
84
|
+
self.update_progress(int((page_num + 1) / total_pages * 100))
|
|
85
|
+
if self._cancel_requested:
|
|
86
|
+
return False, self.language_manager.get(
|
|
87
|
+
"op_word_cancelled", "Operation cancelled"
|
|
88
|
+
) if self.language_manager else "Operation cancelled"
|
|
89
|
+
|
|
90
|
+
page = reader.pages[page_num]
|
|
91
|
+
text = page.extract_text()
|
|
92
|
+
|
|
93
|
+
# Add page content to document
|
|
94
|
+
doc.add_heading(f"Page {page_num + 1}", level=1)
|
|
95
|
+
if text.strip():
|
|
96
|
+
doc.add_paragraph(text)
|
|
97
|
+
else:
|
|
98
|
+
doc.add_paragraph("[No text content detected on this page]")
|
|
99
|
+
|
|
100
|
+
# Try to extract images using pypdfium2 if available
|
|
101
|
+
if pdfium and Image:
|
|
102
|
+
try:
|
|
103
|
+
# Open PDF and render single page
|
|
104
|
+
pdf = pdfium.PdfDocument(input_path)
|
|
105
|
+
if page_num < len(pdf):
|
|
106
|
+
page = pdf[page_num]
|
|
107
|
+
pil_image = page.render(scale=2.0).to_pil()
|
|
108
|
+
|
|
109
|
+
# Save image temporarily
|
|
110
|
+
tmp_fd = None
|
|
111
|
+
tmp_name = None
|
|
112
|
+
try:
|
|
113
|
+
tmp_fd, tmp_name = tmp_mkstemp(suffix=".png")
|
|
114
|
+
os.close(tmp_fd)
|
|
115
|
+
tmp_fd = None
|
|
116
|
+
pil_image.save(tmp_name, "PNG")
|
|
117
|
+
doc.add_picture(tmp_name, width=Inches(6))
|
|
118
|
+
except Exception:
|
|
119
|
+
pass
|
|
120
|
+
finally:
|
|
121
|
+
if tmp_fd is not None:
|
|
122
|
+
try:
|
|
123
|
+
os.close(tmp_fd)
|
|
124
|
+
except Exception:
|
|
125
|
+
pass
|
|
126
|
+
if tmp_name and os_path.exists(tmp_name):
|
|
127
|
+
try:
|
|
128
|
+
os.remove(tmp_name)
|
|
129
|
+
except Exception:
|
|
130
|
+
pass
|
|
131
|
+
pdf.close()
|
|
132
|
+
except Exception:
|
|
133
|
+
pass # Continue without images if conversion fails
|
|
134
|
+
|
|
135
|
+
# Save Word document atomically
|
|
136
|
+
def _save_docx(tmp_path):
|
|
137
|
+
doc.save(tmp_path)
|
|
138
|
+
|
|
139
|
+
if self._atomic_write_via_path:
|
|
140
|
+
self._atomic_write_via_path(output_path, _save_docx)
|
|
141
|
+
else:
|
|
142
|
+
doc.save(output_path)
|
|
143
|
+
|
|
144
|
+
success_msg = (
|
|
145
|
+
self.language_manager.get("op_word_success", "PDF converted to Word document: {output_path}")
|
|
146
|
+
if self.language_manager
|
|
147
|
+
else "PDF converted to Word document: {output_path}"
|
|
148
|
+
)
|
|
149
|
+
return True, success_msg.format(output_path=output_path)
|
|
150
|
+
|
|
151
|
+
except Exception as e:
|
|
152
|
+
error_msg = (
|
|
153
|
+
self.language_manager.get("op_word_failed", "PDF to Word conversion failed: {error}")
|
|
154
|
+
if self.language_manager
|
|
155
|
+
else "PDF to Word conversion failed: {error}"
|
|
156
|
+
)
|
|
157
|
+
return False, error_msg.format(error=str(e))
|
SafePDF/ops/pdf2jpeg.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""
|
|
2
|
+
PDF to JPEG Conversion Module for SafePDF
|
|
3
|
+
Handles PDF to JPEG/JPG image conversion operations
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from os import path as os_path
|
|
7
|
+
from typing import Tuple
|
|
8
|
+
|
|
9
|
+
import pypdfium2 as pdfium
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
from SafePDF.logger.logging_config import get_logger
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PDFToJPEGConverter:
|
|
16
|
+
"""Class handling PDF to JPEG conversion operations"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, progress_callback=None, language_manager=None):
|
|
19
|
+
"""
|
|
20
|
+
Initialize PDF to JPEG converter
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
progress_callback: Function to call for progress updates (0-100)
|
|
24
|
+
language_manager: Language manager for localization
|
|
25
|
+
"""
|
|
26
|
+
self.progress_callback = progress_callback
|
|
27
|
+
self.language_manager = language_manager
|
|
28
|
+
self._cancel_requested = False
|
|
29
|
+
self.logger = get_logger("SafePDF.PDF2JPEG")
|
|
30
|
+
|
|
31
|
+
def update_progress(self, value):
|
|
32
|
+
"""Update progress if callback is available"""
|
|
33
|
+
if self.progress_callback:
|
|
34
|
+
self.progress_callback(value)
|
|
35
|
+
|
|
36
|
+
def request_cancel(self):
|
|
37
|
+
"""Request cancellation of a running operation."""
|
|
38
|
+
self._cancel_requested = True
|
|
39
|
+
|
|
40
|
+
def pdf_to_jpg(self, input_path: str, output_dir: str, dpi: int = 200) -> Tuple[bool, str]:
|
|
41
|
+
"""
|
|
42
|
+
Convert PDF pages to JPG images using pypdfium2
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
input_path: Input PDF file path
|
|
46
|
+
output_dir: Directory to save JPG files
|
|
47
|
+
dpi: Resolution for images (scale factor)
|
|
48
|
+
|
|
49
|
+
Returns:
|
|
50
|
+
Tuple of (success, message)
|
|
51
|
+
"""
|
|
52
|
+
try:
|
|
53
|
+
if not pdfium:
|
|
54
|
+
return False, self.language_manager.get(
|
|
55
|
+
"op_pypdfium_unavailable", "pypdfium2 not available. Install with: pip install pypdfium2"
|
|
56
|
+
) if self.language_manager else "pypdfium2 not available. Install with: pip install pypdfium2"
|
|
57
|
+
|
|
58
|
+
if not Image:
|
|
59
|
+
return False, self.language_manager.get(
|
|
60
|
+
"op_pil_unavailable", "PIL/Pillow not available"
|
|
61
|
+
) if self.language_manager else "PIL/Pillow not available"
|
|
62
|
+
|
|
63
|
+
self.update_progress(10)
|
|
64
|
+
|
|
65
|
+
# Open PDF with pypdfium2
|
|
66
|
+
try:
|
|
67
|
+
pdf = pdfium.PdfDocument(input_path)
|
|
68
|
+
except Exception as e:
|
|
69
|
+
error_msg = (
|
|
70
|
+
self.language_manager.get("op_pdf_open_failed", "Failed to open PDF: {error}")
|
|
71
|
+
if self.language_manager
|
|
72
|
+
else "Failed to open PDF: {error}"
|
|
73
|
+
)
|
|
74
|
+
return False, error_msg.format(error=str(e))
|
|
75
|
+
|
|
76
|
+
total_pages = len(pdf)
|
|
77
|
+
self.update_progress(20)
|
|
78
|
+
|
|
79
|
+
# Calculate scale from DPI (72 DPI is default)
|
|
80
|
+
scale = dpi / 72.0
|
|
81
|
+
|
|
82
|
+
for page_num in range(total_pages):
|
|
83
|
+
if self._cancel_requested:
|
|
84
|
+
pdf.close()
|
|
85
|
+
return False, self.language_manager.get(
|
|
86
|
+
"op_cancelled", "Operation cancelled by user"
|
|
87
|
+
) if self.language_manager else "Operation cancelled by user"
|
|
88
|
+
|
|
89
|
+
# Render page to PIL Image
|
|
90
|
+
page = pdf[page_num]
|
|
91
|
+
pil_image = page.render(scale=scale).to_pil()
|
|
92
|
+
|
|
93
|
+
# Save as JPG
|
|
94
|
+
output_filename = f"page_{page_num + 1}.jpg"
|
|
95
|
+
output_path = os_path.join(output_dir, output_filename)
|
|
96
|
+
pil_image.save(output_path, "JPEG", quality=95, optimize=True)
|
|
97
|
+
|
|
98
|
+
self.update_progress(20 + (70 * page_num // total_pages))
|
|
99
|
+
|
|
100
|
+
pdf.close()
|
|
101
|
+
self.update_progress(100)
|
|
102
|
+
|
|
103
|
+
success_msg = (
|
|
104
|
+
self.language_manager.get("op_jpg_success", "Converted {total_pages} pages to JPG images")
|
|
105
|
+
if self.language_manager
|
|
106
|
+
else "Converted {total_pages} pages to JPG images"
|
|
107
|
+
)
|
|
108
|
+
return True, success_msg.format(total_pages=total_pages)
|
|
109
|
+
|
|
110
|
+
except Exception as e:
|
|
111
|
+
error_msg = (
|
|
112
|
+
self.language_manager.get("op_jpg_failed", "PDF to JPG conversion failed: {error}")
|
|
113
|
+
if self.language_manager
|
|
114
|
+
else "PDF to JPG conversion failed: {error}"
|
|
115
|
+
)
|
|
116
|
+
return False, error_msg.format(error=str(e))
|