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
+ class Config :
11
+ """Configuration parameters."""
12
+ CREDENTIALS_FILE = Path (r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json" )
13
+ LOCAL_FOLDER = Path (r"C:\Samples" )
14
+ PDF_DOCUMENT_NAME = "sample_file_with_attachment.pdf"
15
+ ATTACHMENT_PATH = ""
16
+
17
+ class PdfAttachments :
18
+ """Class for managing PDF attachments using Aspose PDF Cloud API."""
19
+ def __init__ (self , credentials_file : Path = Config .CREDENTIALS_FILE ):
20
+ self .pdf_api = None
21
+ self ._init_api (credentials_file )
22
+
23
+ def _init_api (self , credentials_file : Path ):
24
+ """Initialize the API client."""
25
+ try :
26
+ with credentials_file .open ("r" , encoding = "utf-8" ) as file :
27
+ credentials = json .load (file )
28
+ api_key , app_id = credentials .get ("key" ), credentials .get ("id" )
29
+ if not api_key or not app_id :
30
+ raise ValueError ("init_api(): Error: Missing API keys in the credentials file." )
31
+ self .pdf_api = PdfApi (ApiClient (api_key , app_id ))
32
+ except (FileNotFoundError , json .JSONDecodeError , ValueError ) as e :
33
+ logging .error (f"init_api(): Failed to load credentials: { e } " )
34
+
35
+ def upload_document (self ):
36
+ """Upload a PDF document to the Aspose Cloud server."""
37
+ if self .pdf_api :
38
+ file_path = Config .LOCAL_FOLDER / Config .PDF_DOCUMENT_NAME
39
+ try :
40
+ self .pdf_api .upload_file (Config .PDF_DOCUMENT_NAME , str (file_path ))
41
+ logging .info (f"upload_document(): File { Config .PDF_DOCUMENT_NAME } uploaded successfully." )
42
+ except Exception as e :
43
+ logging .error (f"upload_document(): Failed to upload file: { e } " )
44
+
45
+ def get_attachments (self ):
46
+ """Get attachments for the PDF document."""
47
+ if self .pdf_api :
48
+ try :
49
+ response : AttachmentsResponse = self .pdf_api .get_document_attachments (Config .PDF_DOCUMENT_NAME )
50
+ if response .code == 200 :
51
+ logging .info (f"get_attachmnets(): attachments '{ response .attachments } ' for the document '{ Config .PDF_DOCUMENT_NAME } '." )
52
+ Config .ATTACHMENT_PATH = response .attachments .list [0 ].links [0 ].href
53
+ else :
54
+ logging .error (f"get_attachmnets(): Failed to get attachments to the document. Response code: { response .code } " )
55
+ except Exception as e :
56
+ logging .error (f"get_attachmnets(): Error while adding attachment: { e } " )
57
+
58
+ def get_attachment_by_id (self ):
59
+ """Get attachment by Id for the PDF document and save it to local file."""
60
+ if self .pdf_api :
61
+ try :
62
+ response : AttachmentResponse = self .pdf_api .get_document_attachment_by_index (Config .PDF_DOCUMENT_NAME , Config .ATTACHMENT_PATH )
63
+ if response .code == 200 :
64
+ attachment : Attachment = response .attachment
65
+ temp_file = self .pdf_api .get_download_document_attachment_by_index (Config .PDF_DOCUMENT_NAME , Config .ATTACHMENT_PATH )
66
+ local_path = Config .LOCAL_FOLDER / attachment .name
67
+ shutil .copy (temp_file , local_path )
68
+ logging .info (f"get_attachment_by_id(): attachment '{ local_path } ' for the document '{ Config .PDF_DOCUMENT_NAME } ' successfuly saved." )
69
+ else :
70
+ logging .error (f"get_attachment_by_id(): Failed to get attachment for the document '{ Config .PDF_DOCUMENT_NAME } '. Response code: { response .code } " )
71
+ except Exception as e :
72
+ logging .error (f"get_attachment_by_id(): Error while get attachment: { e } " )
73
+
74
+
75
+ if __name__ == "__main__" :
76
+ pdf_attachments = PdfAttachments ()
77
+ pdf_attachments .upload_document ()
78
+ pdf_attachments .get_attachments ()
79
+ pdf_attachments .get_attachment_by_id ()
0 commit comments