Skip to content

Commit df6314a

Browse files
authored
Merge pull request #95 from aspose-pdf-cloud/pdfcloud-4784-added-use-cases-for-encrypt-decrypt
PDFCLOUD-4784: added use cases for Encrypt/Decrypt
2 parents 86b9ccc + ed3f2dd commit df6314a

File tree

2 files changed

+158
-0
lines changed

2 files changed

+158
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
import base64
6+
from asposepdfcloud import ApiClient, PdfApi, CryptoAlgorithm
7+
8+
# Configure logging
9+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
10+
11+
class Config:
12+
"""Configuration parameters."""
13+
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
14+
LOCAL_FOLDER = Path(r"C:\Samples")
15+
PDF_DOCUMENT_NAME = "sample_encrypted.pdf"
16+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
17+
DOCUMENT_PASSWORD = 'Owner-Password'
18+
19+
class pdfEncryption:
20+
"""Class for managing PDF encryption using Aspose PDF Cloud API."""
21+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
22+
self.pdf_api = None
23+
self._init_api(credentials_file)
24+
25+
def _init_api(self, credentials_file: Path):
26+
"""Initialize the API client."""
27+
try:
28+
with credentials_file.open("r", encoding="utf-8") as file:
29+
credentials = json.load(file)
30+
api_key, app_id = credentials.get("key"), credentials.get("id")
31+
if not api_key or not app_id:
32+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
33+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
34+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
35+
logging.error(f"init_api(): Failed to load credentials: {e}")
36+
37+
def upload_document(self):
38+
""" Upload a PDF document to the Aspose Cloud server. """
39+
if self.pdf_api:
40+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
41+
try:
42+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
43+
logging.info(f"upload_file(): File '{Config.PDF_DOCUMENT_NAME}' uploaded successfully.")
44+
except Exception as e:
45+
logging.error(f"upload_document(): Failed to upload file: {e}")
46+
47+
def download_result(self):
48+
""" Download the processed PDF document from the Aspose Cloud server. """
49+
if self.pdf_api:
50+
try:
51+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
52+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
53+
shutil.move(temp_file, str(local_path))
54+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
55+
except Exception as e:
56+
logging.error(f"download_result(): Failed to download file: {e}")
57+
58+
def decrypt_document(self):
59+
"""Decrypt the PDF document."""
60+
if self.pdf_api:
61+
try:
62+
password_encoded = base64.b64encode(bytes(Config.DOCUMENT_PASSWORD, encoding='utf-8'))
63+
64+
response = self.pdf_api.post_decrypt_document_in_storage(Config.PDF_DOCUMENT_NAME, password_encoded)
65+
if response.code == 200:
66+
logging.info(f"decrypt_document(): Document #{Config.PDF_DOCUMENT_NAME} successfully decrypted.")
67+
else:
68+
logging.error(f"decrypt_document(): Failed to decrypt document #{Config.PDF_DOCUMENT_NAME}. Response code: {response.code}")
69+
except Exception as e:
70+
logging.error(f"decrypt_document(): Error while decrypted document: {e}")
71+
72+
73+
if __name__ == "__main__":
74+
pdf_encrypt = pdfEncryption()
75+
pdf_encrypt.upload_document()
76+
pdf_encrypt.decrypt_document()
77+
pdf_encrypt.download_result()
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
import base64
6+
from asposepdfcloud import ApiClient, PdfApi, CryptoAlgorithm
7+
8+
# Configure logging
9+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
10+
11+
class Config:
12+
"""Configuration parameters."""
13+
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
14+
LOCAL_FOLDER = Path(r"C:\Samples")
15+
PDF_DOCUMENT_NAME = "sample.pdf"
16+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
17+
ENCRYPT_ALGORITHM = CryptoAlgorithm.AESX256
18+
USER_PASSWORD = 'User-Password'
19+
OWNER_PASSWORD = 'Owner-Password'
20+
21+
class pdfEncryption:
22+
"""Class for managing PDF encryption using Aspose PDF Cloud API."""
23+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
24+
self.pdf_api = None
25+
self._init_api(credentials_file)
26+
27+
def _init_api(self, credentials_file: Path):
28+
"""Initialize the API client."""
29+
try:
30+
with credentials_file.open("r", encoding="utf-8") as file:
31+
credentials = json.load(file)
32+
api_key, app_id = credentials.get("key"), credentials.get("id")
33+
if not api_key or not app_id:
34+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
35+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
36+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
37+
logging.error(f"init_api(): Failed to load credentials: {e}")
38+
39+
def upload_document(self):
40+
""" Upload a PDF document to the Aspose Cloud server. """
41+
if self.pdf_api:
42+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
43+
try:
44+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
45+
logging.info(f"upload_file(): File '{Config.PDF_DOCUMENT_NAME}' uploaded successfully.")
46+
except Exception as e:
47+
logging.error(f"upload_document(): Failed to upload file: {e}")
48+
49+
def download_result(self):
50+
""" Download the processed PDF document from the Aspose Cloud server. """
51+
if self.pdf_api:
52+
try:
53+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
54+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
55+
shutil.move(temp_file, str(local_path))
56+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
57+
except Exception as e:
58+
logging.error(f"download_result(): Failed to download file: {e}")
59+
60+
def encrypt_document(self):
61+
"""Encrypt the PDF document."""
62+
if self.pdf_api:
63+
try:
64+
user_password_encoded = base64.b64encode(bytes(Config.USER_PASSWORD, encoding='utf-8'))
65+
66+
owner_password_encoded = base64.b64encode(bytes(Config.OWNER_PASSWORD, encoding='utf-8'))
67+
68+
response = self.pdf_api.post_encrypt_document_in_storage(Config.PDF_DOCUMENT_NAME, user_password_encoded, owner_password_encoded, Config.ENCRYPT_ALGORITHM)
69+
if response.code == 200:
70+
logging.info(f"encrypt_document(): Document #{Config.PDF_DOCUMENT_NAME} successfully encrypted.")
71+
else:
72+
logging.error(f"encrypt_document(): Failed to encrypt document #{Config.PDF_DOCUMENT_NAME}. Response code: {response.code}")
73+
except Exception as e:
74+
logging.error(f"aencrypt_document(): Error while encrypted document: {e}")
75+
76+
77+
if __name__ == "__main__":
78+
pdf_encrypt = pdfEncryption()
79+
pdf_encrypt.upload_document()
80+
pdf_encrypt.encrypt_document()
81+
pdf_encrypt.download_result()

0 commit comments

Comments
 (0)