Skip to content

Commit ab2a21b

Browse files
PDFAPPS-6716: added use cases for Bookmarks
1 parent 2e97e76 commit ab2a21b

File tree

5 files changed

+473
-0
lines changed

5 files changed

+473
-0
lines changed
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, Link, 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 = "• Підвищення продуктивності: Автоматизація дозволяє виконувати багато завдань швидше та ефективніше, ніж це може зробити людина. Це особливо важливо в промислових галузях, де швидкість та точність відіграють вирішальну роль." #"• 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 _ensure_api_initialized(self):
42+
"""Check if the API is initialized before making API calls."""
43+
if not self.pdf_api:
44+
logging.error("ensure_api_initialized(): PDF API is not initialized. Operation aborted.")
45+
return False
46+
return True
47+
48+
def upload_document(self):
49+
"""Upload a PDF document to the Aspose Cloud server."""
50+
if not self._ensure_api_initialized():
51+
return
52+
53+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
54+
try:
55+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
56+
logging.info(f"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
57+
except Exception as e:
58+
logging.error(f"upload_document(): Failed to upload file: {e}")
59+
60+
def download_result(self):
61+
"""Download the processed PDF document from the Aspose Cloud server."""
62+
if not self._ensure_api_initialized():
63+
return
64+
65+
try:
66+
file_path = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
67+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
68+
shutil.move(file_path, str(local_path))
69+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
70+
except Exception as e:
71+
logging.error(f"download_result(): Failed to download file: {e}")
72+
73+
def append_bookmark_link(self):
74+
"""Append a new bookmark link to a specific page in the PDF document."""
75+
if not self._ensure_api_initialized():
76+
return
77+
78+
newBookmark = Bookmark(
79+
title = Config.NEW_BOOKMARK_TITLE,
80+
italic = True,
81+
bold = True,
82+
color = Color(a=255,r=0,g=255,b=0),
83+
level = 1,
84+
page_display_left = Config.BOOKMARK_PAGE_POSITION_X,
85+
page_display_top = Config.BOOKMARK_PAGE_POSITION_Y,
86+
page_display_zoom = 2,
87+
page_number = Config.NEW_BOOKMARK_PAGE_NUMBER
88+
)
89+
90+
try:
91+
response = self.pdf_api.post_bookmark(
92+
Config.PDF_DOCUMENT_NAME, Config.PARENT_BOOKMARK_FOR_APPEND, [newBookmark]
93+
)
94+
if response.code == 200:
95+
logging.info(f"append_bookmark_link(): Bookmark '{response.bookmarks.list[0].action}'->'{Config.NEW_BOOKMARK_TITLE}' added to page #{Config.NEW_BOOKMARK_PAGE_NUMBER}.")
96+
else:
97+
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}")
98+
except Exception as e:
99+
logging.error(f"append_bookmark_link(): Error while adding bookmark: {e}")
100+
101+
102+
if __name__ == "__main__":
103+
pdf_bookmarks = PdfBookmarks()
104+
pdf_bookmarks.upload_document()
105+
pdf_bookmarks.append_bookmark_link()
106+
pdf_bookmarks.download_result()
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
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 _ensure_api_initialized(self):
38+
"""Check if the API is initialized before making API calls."""
39+
if not self.pdf_api:
40+
logging.error("PDF API is not initialized. Operation aborted.")
41+
return False
42+
return True
43+
44+
def upload_document(self):
45+
"""Upload a PDF document to the Aspose Cloud server."""
46+
if not self._ensure_api_initialized():
47+
return
48+
49+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
50+
try:
51+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
52+
logging.info(f"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
53+
except Exception as e:
54+
logging.error(f"Failed to upload file: {e}")
55+
56+
def get_bookmark(self):
57+
"""Get bookmark for a specific PDF document using bookmark path."""
58+
if not self._ensure_api_initialized():
59+
return
60+
61+
try:
62+
response : BookmarkResponse = self.pdf_api.get_bookmark( Config.PDF_DOCUMENT_NAME, Config.BOOKMARK_PATH)
63+
if response.code == 200:
64+
logging.info(f"Found bookmark => level: '{response.bookmark.level}' - action: '{response.bookmark.action}' - title: '{response.bookmark.title}'")
65+
else:
66+
logging.error(f"Failed to find bookmark for the document. Response code: {response.code}")
67+
except Exception as e:
68+
logging.error(f"Error while find bookmark: {e}")
69+
70+
if __name__ == "__main__":
71+
pdf_bookmarks = PdfBookmarks()
72+
pdf_bookmarks.upload_document()
73+
pdf_bookmarks.get_bookmark()
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, Bookmarks, BookmarksResponse
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+
17+
class PdfBookmarks:
18+
"""Class for managing PDF bookmarks using Aspose PDF Cloud API."""
19+
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("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"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("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"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
52+
except Exception as e:
53+
logging.error(f"Failed to upload file: {e}")
54+
55+
def show_bookmarks_array(self, bookmarks, prefix):
56+
for item in bookmarks.list:
57+
logging.info(f"{prefix} => level: '{item.level}' - action: '{item.action}' - title: '{item.title}'")
58+
if item.bookmarks and item.bookmarks.list and item.bookmarks.list.length > 0:
59+
self.show_bookmarks_array(bookmarks=item.bookmarks, prefix=prefix)
60+
61+
def get_all_bookmarks(self):
62+
"""Get all bookmarks for a specific PDF document."""
63+
if not self._ensure_api_initialized():
64+
return
65+
66+
try:
67+
response : BookmarksResponse = self.pdf_api.get_document_bookmarks( Config.PDF_DOCUMENT_NAME)
68+
if response.code == 200:
69+
self.show_bookmarks_array(response.bookmarks, "All")
70+
else:
71+
logging.error(f"Failed to get bookmarks for the document. Response code: {response.code}")
72+
except Exception as e:
73+
logging.error(f"Error while retrieving bookmarks array: {e}")
74+
75+
if __name__ == "__main__":
76+
pdf_bookmarks = PdfBookmarks()
77+
pdf_bookmarks.upload_document()
78+
pdf_bookmarks.get_all_bookmarks()
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, AsposeResponse
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+
BOOKMARK_PATH = "/1"
18+
19+
20+
class PdfBookmarks:
21+
"""Class for managing PDF bookmarks 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 _ensure_api_initialized(self):
40+
"""Check if the API is initialized before making API calls."""
41+
if not self.pdf_api:
42+
logging.error("PDF API is not initialized. Operation aborted.")
43+
return False
44+
return True
45+
46+
def upload_document(self):
47+
"""Upload a PDF document to the Aspose Cloud server."""
48+
if not self._ensure_api_initialized():
49+
return
50+
51+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
52+
try:
53+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
54+
logging.info(f"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
55+
except Exception as e:
56+
logging.error(f"Failed to upload file: {e}")
57+
58+
def download_result(self):
59+
"""Download the processed PDF document from the Aspose Cloud server."""
60+
if not self._ensure_api_initialized():
61+
return
62+
63+
try:
64+
file_path = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
65+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
66+
shutil.move(file_path, str(local_path))
67+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
68+
except Exception as e:
69+
logging.error(f"download_result(): Failed to download file: {e}")
70+
71+
def remove_bookmark_by_path(self):
72+
if not self.pdf_api:
73+
return
74+
75+
response: AsposeResponse = self.pdf_api.delete_bookmark(Config.PDF_DOCUMENT_NAME, Config.BOOKMARK_PATH)
76+
77+
if response.code == 200:
78+
logging.info(f"Bookmark with path: '{Config.BOOKMARK_PATH}' has been removed.")
79+
else:
80+
logging.erro(f"Failed to remove bookmark with path: '{Config.LINK_FIND_ID}'.")
81+
82+
if __name__ == "__main__":
83+
pdf_bookmarks = PdfBookmarks()
84+
pdf_bookmarks.upload_document()
85+
pdf_bookmarks.remove_bookmark_by_path()
86+
pdf_bookmarks.download_result()

0 commit comments

Comments
 (0)