Skip to content

Commit 43f5619

Browse files
Add files via upload
1 parent e591b2d commit 43f5619

File tree

1 file changed

+118
-0
lines changed

1 file changed

+118
-0
lines changed
Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, Bookmark, BookmarksResponse, BookmarkResponse
6+
7+
class Config:
8+
"""Configuration parameters."""
9+
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
10+
LOCAL_FOLDER = Path(r"C:\\Samples")
11+
PDF_DOCUMENT_NAME = "sample.pdf"
12+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
13+
NEW_BOOKMARK_TITLE = "• Підвищення продуктивності: Автоматизація дозволяє виконувати багато завдань швидше та ефективніше, ніж це може зробити людина. Це особливо важливо в промислових галузях, де швидкість та точність відіграють вирішальну роль." #"• Productivity improvement"
14+
BOOKMARK_PATH = "/5"
15+
NEW_BOOKMARK_PAGE_NUMBER = 3
16+
17+
# Configure logging
18+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
19+
20+
class PdfBookmarks:
21+
"""Class for managing PDF bookmarkss using Aspose PDF Cloud API."""
22+
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("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"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"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
46+
except Exception as e:
47+
logging.error(f"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 show_bookmarks_array(self, bookmarks, prefix):
61+
for item in bookmarks.list:
62+
logging.info(f"{prefix} => level: '{item.level}' - action: '{item.action}' - title: '{item.title}'")
63+
if item.bookmarks and item.bookmarks.list and item.bookmarks.list.length > 0:
64+
self.show_bookmarks_array(bookmarks=item.bookmarks, prefix=prefix)
65+
66+
def get_all_bookmarks(self):
67+
"""Get all bookmarks for a specific PDF document."""
68+
if self.pdf_api:
69+
try:
70+
response : BookmarksResponse = self.pdf_api.get_document_bookmarks( Config.PDF_DOCUMENT_NAME)
71+
if response.code == 200:
72+
self.show_bookmarks_array(response.bookmarks, "All")
73+
else:
74+
logging.error(f"Failed to get bookmarks for the document. Response code: {response.code}")
75+
except Exception as e:
76+
logging.error(f"Error while retrieving bookmarks array: {e}")
77+
78+
def get_bookmark(self):
79+
"""Get bookmark for a specific PDF document using bookmark path."""
80+
if self.pdf_api:
81+
try:
82+
response : BookmarkResponse = self.pdf_api.get_bookmark( Config.PDF_DOCUMENT_NAME, Config.BOOKMARK_PATH)
83+
if response.code == 200:
84+
logging.info(f"Found bookmark => level: '{response.bookmark.level}' - action: '{response.bookmark.action}' - title: '{response.bookmark.title}'")
85+
return response.bookmark
86+
else:
87+
logging.error(f"Failed to find bookmark for the document. Response code: {response.code}")
88+
return None
89+
except Exception as e:
90+
logging.error(f"Error while find bookmark: {e}")
91+
92+
def replace_bookmark(self):
93+
if self.pdf_api:
94+
_bookmark: BookmarkResponse = self.get_bookmark()
95+
96+
if not _bookmark:
97+
return
98+
99+
_bookmark.title = Config.NEW_BOOKMARK_TITLE
100+
101+
response: BookmarkResponse = self.pdf_api.put_bookmark(
102+
Config.PDF_DOCUMENT_NAME,
103+
Config.BOOKMARK_PATH,
104+
bookmark=_bookmark,
105+
)
106+
107+
if response.code == 200:
108+
print("Bookmark replaced successfully.")
109+
else:
110+
print("Failed to replace Bookmark.")
111+
112+
113+
if __name__ == "__main__":
114+
pdf_bookmarks = PdfBookmarks()
115+
pdf_bookmarks.upload_document()
116+
pdf_bookmarks.get_all_bookmarks()
117+
pdf_bookmarks.replace_bookmark()
118+
pdf_bookmarks.download_result()

0 commit comments

Comments
 (0)