Skip to content

Commit 08c622c

Browse files
authored
Merge pull request #92 from aspose-pdf-cloud/develop
Develop
2 parents 54c60c1 + 0f63d86 commit 08c622c

28 files changed

+2159
-5
lines changed

README.md

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,8 @@ XLS, XLSX, PPTX, DOC, DOCX, MobiXML, JPEG, EMF, PNG, BMP, GIF, TIFF, Text
3030
## Read PDF Formats
3131
MHT, PCL, PS, XSLFO, MD
3232

33-
## Enhancements in Version 25.1
33+
## Enhancements in Version 25.2
3434
- A new version of Aspose.PDF Cloud was prepared using the latest version of Aspose.PDF for .NET.
35-
3635
## Requirements.
3736
Python 2.7 and 3.4+
3837

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
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 upload_file(self, fileName: str):
40+
""" Upload a local fileName to the Aspose Cloud server. """
41+
if self.pdf_api:
42+
file_path = Config.LOCAL_FOLDER / fileName
43+
try:
44+
self.pdf_api.upload_file(fileName, str(file_path))
45+
logging.info(f"upload_file(): File '{fileName}' uploaded successfully.")
46+
except Exception as e:
47+
logging.error(f"upload_document(): Failed to upload file: {e}")
48+
49+
def upload_document(self):
50+
""" Upload a PDF document to the Aspose Cloud server. """
51+
self.upload_file(Config.PDF_DOCUMENT_NAME)
52+
53+
def download_result(self):
54+
""" Download the processed PDF document from the Aspose Cloud server. """
55+
if self.pdf_api:
56+
try:
57+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
58+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
59+
shutil.move(temp_file, str(local_path))
60+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
61+
except Exception as e:
62+
logging.error(f"download_result(): Failed to download file: {e}")
63+
64+
def append_attachmnet(self):
65+
"""Append a new attachment to the PDF document."""
66+
if self.pdf_api:
67+
new_attachment = AttachmentInfo(
68+
path = Config.NEW_ATTACHMENT_FILE,
69+
description = 'This is a sample attachment',
70+
mime_type = Config.NEW_ATTACHMENT_MIME,
71+
name = Config.NEW_ATTACHMENT_FILE
72+
)
73+
74+
try:
75+
response = self.pdf_api.post_add_document_attachment(Config.PDF_DOCUMENT_NAME, new_attachment)
76+
if response.code == 200:
77+
logging.info(f"append_attachment(): attachment '{Config.NEW_ATTACHMENT_FILE}' added to the document '{Config.PDF_DOCUMENT_NAME}'.")
78+
else:
79+
logging.error(f"append_attachment(): Failed to add attachment to the document. Response code: {response.code}")
80+
except Exception as e:
81+
logging.error(f"append_attachment(): Error while adding attachment: {e}")
82+
83+
84+
if __name__ == "__main__":
85+
pdf_attachments = PdfAttachments()
86+
pdf_attachments.upload_document()
87+
pdf_attachments.upload_file(Config.NEW_ATTACHMENT_FILE)
88+
pdf_attachments.append_attachmnet()
89+
pdf_attachments.download_result()
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
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()
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, Color, Bookmark
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.pdf"
15+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
16+
NEW_BOOKMARK_TITLE = "• Increased performance.." #"• Productivity improvement"
17+
PARENT_BOOKMARK_FOR_APPEND = "" #The parent bookmark path. Specify an empty string when adding a bookmark to the root.
18+
NEW_BOOKMARK_PAGE_NUMBER = 3
19+
BOOKMARK_PAGE_POSITION_X = 89
20+
BOOKMARK_PAGE_POSITION_Y = 564
21+
22+
23+
class PdfBookmarks:
24+
"""Class for managing PDF bokkmarks using Aspose PDF Cloud API."""
25+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
26+
self.pdf_api = None
27+
self._init_api(credentials_file)
28+
29+
def _init_api(self, credentials_file: Path):
30+
"""Initialize the API client."""
31+
try:
32+
with credentials_file.open("r", encoding="utf-8") as file:
33+
credentials = json.load(file)
34+
api_key, app_id = credentials.get("key"), credentials.get("id")
35+
if not api_key or not app_id:
36+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
37+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
38+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
39+
logging.error(f"init_api(): Failed to load credentials: {e}")
40+
41+
def upload_document(self):
42+
"""Upload a PDF document to the Aspose Cloud server."""
43+
if self.pdf_api:
44+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
45+
try:
46+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
47+
logging.info(f"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
48+
except Exception as e:
49+
logging.error(f"upload_document(): Failed to upload file: {e}")
50+
51+
def download_result(self):
52+
"""Download the processed PDF document from the Aspose Cloud server."""
53+
if self.pdf_api:
54+
try:
55+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
56+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
57+
shutil.move(temp_file, str(local_path))
58+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
59+
except Exception as e:
60+
logging.error(f"download_result(): Failed to download file: {e}")
61+
62+
def append_bookmark_link(self):
63+
"""Append a new bookmark link to a specific page in the PDF document."""
64+
if self.pdf_api:
65+
newBookmark = Bookmark(
66+
title = Config.NEW_BOOKMARK_TITLE,
67+
italic = True,
68+
bold = True,
69+
color = Color(a=255,r=0,g=255,b=0),
70+
level = 1,
71+
page_display_left = Config.BOOKMARK_PAGE_POSITION_X,
72+
page_display_top = Config.BOOKMARK_PAGE_POSITION_Y,
73+
page_display_zoom = 2,
74+
page_number = Config.NEW_BOOKMARK_PAGE_NUMBER
75+
)
76+
77+
try:
78+
response = self.pdf_api.post_bookmark(
79+
Config.PDF_DOCUMENT_NAME, Config.PARENT_BOOKMARK_FOR_APPEND, [newBookmark]
80+
)
81+
if response.code == 200:
82+
logging.info(f"append_bookmark_link(): Bookmark '{response.bookmarks.list[0].action}'->'{Config.NEW_BOOKMARK_TITLE}' added to page #{Config.NEW_BOOKMARK_PAGE_NUMBER}.")
83+
else:
84+
logging.error(f"append_bookmark_link(): Failed to add bookmark '{Config.NEW_BOOKMARK_TITLE}' to the page #{Config.NEW_BOOKMARK_PAGE_NUMBER}. Response code: {response.code}")
85+
except Exception as e:
86+
logging.error(f"append_bookmark_link(): Error while adding bookmark: {e}")
87+
88+
89+
if __name__ == "__main__":
90+
pdf_bookmarks = PdfBookmarks()
91+
pdf_bookmarks.upload_document()
92+
pdf_bookmarks.append_bookmark_link()
93+
pdf_bookmarks.download_result()
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, BookmarkResponse
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+
BOOKMARK_PATH = "/5"
17+
18+
class PdfBookmarks:
19+
"""Class for managing PDF bookmarks using Aspose PDF Cloud API."""
20+
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("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"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"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
44+
except Exception as e:
45+
logging.error(f"Failed to upload file: {e}")
46+
47+
def get_bookmark(self):
48+
"""Get bookmark for a specific PDF document using bookmark path."""
49+
if self.pdf_api:
50+
try:
51+
response : BookmarkResponse = self.pdf_api.get_bookmark( Config.PDF_DOCUMENT_NAME, Config.BOOKMARK_PATH)
52+
if response.code == 200:
53+
logging.info(f"Found bookmark => level: '{response.bookmark.level}' - action: '{response.bookmark.action}' - title: '{response.bookmark.title}'")
54+
else:
55+
logging.error(f"Failed to find bookmark for the document. Response code: {response.code}")
56+
except Exception as e:
57+
logging.error(f"Error while find bookmark: {e}")
58+
59+
if __name__ == "__main__":
60+
pdf_bookmarks = PdfBookmarks()
61+
pdf_bookmarks.upload_document()
62+
pdf_bookmarks.get_bookmark()

0 commit comments

Comments
 (0)