Skip to content

Commit 97308dd

Browse files
authored
Merge pull request #84 from aspose-pdf-cloud/pdfapps-6711-added-use-cases-for-Attachments
PDFAPPS-6711: added use cases for Attachments
2 parents 2e97e76 + 89387dd commit 97308dd

File tree

2 files changed

+195
-0
lines changed

2 files changed

+195
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, AttachmentInfo
6+
7+
# Configure logging
8+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
9+
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+
NEW_ATTACHMENT_FILE = "sample_video.mp4"
18+
NEW_ATTACHMENT_MIME = "video/mp4"
19+
PAGE_NUMBER = 2
20+
21+
class PdfAttachments:
22+
"""Class for managing PDF attachments 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 _ensure_api_initialized(self):
40+
"""Check if the API is initialized before making API calls."""
41+
if not self.pdf_api:
42+
logging.error("ensure_api_initialized(): PDF API is not initialized. Operation aborted.")
43+
return False
44+
return True
45+
46+
def upload_file(self, fileName: str):
47+
""" Upload a local fileName to the Aspose Cloud server. """
48+
if not self._ensure_api_initialized():
49+
return
50+
51+
file_path = Config.LOCAL_FOLDER / fileName
52+
try:
53+
self.pdf_api.upload_file(fileName, str(file_path))
54+
logging.info(f"upload_file(): File '{fileName}' uploaded successfully.")
55+
except Exception as e:
56+
logging.error(f"upload_document(): Failed to upload file: {e}")
57+
58+
def upload_document(self):
59+
""" Upload a PDF document to the Aspose Cloud server. """
60+
self.upload_file(Config.PDF_DOCUMENT_NAME)
61+
62+
def download_result(self):
63+
""" Download the processed PDF document from the Aspose Cloud server. """
64+
if not self._ensure_api_initialized():
65+
return
66+
67+
try:
68+
file_path = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
69+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
70+
shutil.move(file_path, str(local_path))
71+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
72+
except Exception as e:
73+
logging.error(f"download_result(): Failed to download file: {e}")
74+
75+
def append_attachmnet(self):
76+
"""Append a new attachment to the PDF document."""
77+
if not self._ensure_api_initialized():
78+
return
79+
80+
new_attachment = AttachmentInfo(
81+
path = Config.NEW_ATTACHMENT_FILE,
82+
description = 'This is a sample attachment',
83+
mime_type = Config.NEW_ATTACHMENT_MIME,
84+
name = Config.NEW_ATTACHMENT_FILE
85+
)
86+
87+
try:
88+
response = self.pdf_api.post_add_document_attachment(Config.PDF_DOCUMENT_NAME, new_attachment)
89+
if response.code == 200:
90+
logging.info(f"append_attachment(): attachment '{Config.NEW_ATTACHMENT_FILE}' added to the document '{Config.PDF_DOCUMENT_NAME}'.")
91+
else:
92+
logging.error(f"append_attachment(): Failed to add attachment to the document. Response code: {response.code}")
93+
except Exception as e:
94+
logging.error(f"append_attachment(): Error while adding attachment: {e}")
95+
96+
97+
if __name__ == "__main__":
98+
pdf_attachments = PdfAttachments()
99+
pdf_attachments.upload_document()
100+
pdf_attachments.upload_file(Config.NEW_ATTACHMENT_FILE)
101+
pdf_attachments.append_attachmnet()
102+
pdf_attachments.download_result()
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, AttachmentsResponse, AttachmentResponse, Attachment
6+
7+
# Configure logging
8+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
9+
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_file_with_attachment.pdf"
16+
ATTACHMENT_PATH = ""
17+
18+
class PdfAttachments:
19+
"""Class for managing PDF attachments using Aspose PDF Cloud API."""
20+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
21+
self.pdf_api = None
22+
self._init_api(credentials_file)
23+
24+
def _init_api(self, credentials_file: Path):
25+
"""Initialize the API client."""
26+
try:
27+
with credentials_file.open("r", encoding="utf-8") as file:
28+
credentials = json.load(file)
29+
api_key, app_id = credentials.get("key"), credentials.get("id")
30+
if not api_key or not app_id:
31+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
32+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
33+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
34+
logging.error(f"init_api(): Failed to load credentials: {e}")
35+
36+
def _ensure_api_initialized(self):
37+
"""Check if the API is initialized before making API calls."""
38+
if not self.pdf_api:
39+
logging.error("ensure_api_initialized(): PDF API is not initialized. Operation aborted.")
40+
return False
41+
return True
42+
43+
def upload_document(self):
44+
"""Upload a PDF document to the Aspose Cloud server."""
45+
if not self._ensure_api_initialized():
46+
return
47+
48+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
49+
try:
50+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
51+
logging.info(f"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
52+
except Exception as e:
53+
logging.error(f"upload_document(): Failed to upload file: {e}")
54+
55+
def get_attachments(self):
56+
"""Get attachments for the PDF document."""
57+
if not self._ensure_api_initialized():
58+
return
59+
60+
try:
61+
response : AttachmentsResponse = self.pdf_api.get_document_attachments(Config.PDF_DOCUMENT_NAME)
62+
if response.code == 200:
63+
logging.info(f"get_attachmnets(): attachments '{response.attachments}' for the document '{Config.PDF_DOCUMENT_NAME}'.")
64+
Config.ATTACHMENT_PATH = response.attachments.list[0].links[0].href;
65+
else:
66+
logging.error(f"get_attachmnets(): Failed to get attachments to the document. Response code: {response.code}")
67+
except Exception as e:
68+
logging.error(f"get_attachmnets(): Error while adding attachment: {e}")
69+
70+
def get_attachment_by_id(self):
71+
"""Get attachment by Id for the PDF document and save it to local file."""
72+
if not self._ensure_api_initialized():
73+
return
74+
75+
try:
76+
response : AttachmentResponse = self.pdf_api.get_document_attachment_by_index(Config.PDF_DOCUMENT_NAME, Config.ATTACHMENT_PATH)
77+
if response.code == 200:
78+
attachment: Attachment = response.attachment
79+
file_path = self.pdf_api.get_download_document_attachment_by_index(Config.PDF_DOCUMENT_NAME, Config.ATTACHMENT_PATH)
80+
local_path = Config.LOCAL_FOLDER / attachment.name
81+
shutil.copy(file_path, local_path)
82+
logging.info(f"get_attachmnets(): attachments '{file_path}' for the document '{Config.PDF_DOCUMENT_NAME}' successfuly saved.")
83+
else:
84+
logging.error(f"get_attachmnets(): Failed to get attachments to the document. Response code: {response.code}")
85+
except Exception as e:
86+
logging.error(f"get_attachmnets(): Error while get attachment: {e}")
87+
88+
89+
if __name__ == "__main__":
90+
pdf_attachments = PdfAttachments()
91+
pdf_attachments.upload_document()
92+
pdf_attachments.get_attachments()
93+
pdf_attachments.get_attachment_by_id()

0 commit comments

Comments
 (0)