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 ()
0 commit comments