Skip to content

Commit ab69362

Browse files
authored
Merge pull request #85 from aspose-pdf-cloud/pdfapps-6716-added-use-cases-for-bookmarks
PDFAPPS-6716: added use cases for Bookmarks
2 parents 85da872 + 2e775cf commit ab69362

File tree

5 files changed

+413
-0
lines changed

5 files changed

+413
-0
lines changed
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()
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, 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 upload_document(self):
37+
"""Upload a PDF document to the Aspose Cloud server."""
38+
if self.pdf_api:
39+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
40+
try:
41+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
42+
logging.info(f"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
43+
except Exception as e:
44+
logging.error(f"Failed to upload file: {e}")
45+
46+
def show_bookmarks_array(self, bookmarks, prefix):
47+
for item in bookmarks.list:
48+
logging.info(f"{prefix} => level: '{item.level}' - action: '{item.action}' - title: '{item.title}'")
49+
if item.bookmarks and item.bookmarks.list and item.bookmarks.list.length > 0:
50+
self.show_bookmarks_array(bookmarks=item.bookmarks, prefix=prefix)
51+
52+
def get_all_bookmarks(self):
53+
"""Get all bookmarks for a specific PDF document."""
54+
if self.pdf_api:
55+
try:
56+
response : BookmarksResponse = self.pdf_api.get_document_bookmarks( Config.PDF_DOCUMENT_NAME)
57+
if response.code == 200:
58+
self.show_bookmarks_array(response.bookmarks, "All")
59+
else:
60+
logging.error(f"Failed to get bookmarks for the document. Response code: {response.code}")
61+
except Exception as e:
62+
logging.error(f"Error while retrieving bookmarks array: {e}")
63+
64+
if __name__ == "__main__":
65+
pdf_bookmarks = PdfBookmarks()
66+
pdf_bookmarks.upload_document()
67+
pdf_bookmarks.get_all_bookmarks()
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, 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 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 remove_bookmark_by_path(self):
61+
if self.pdf_api:
62+
response: AsposeResponse = self.pdf_api.delete_bookmark(Config.PDF_DOCUMENT_NAME, Config.BOOKMARK_PATH)
63+
64+
if response.code == 200:
65+
logging.info(f"Bookmark with path: '{Config.BOOKMARK_PATH}' has been removed.")
66+
else:
67+
logging.erro(f"Failed to remove bookmark with path: '{Config.LINK_FIND_ID}")
68+
69+
if __name__ == "__main__":
70+
pdf_bookmarks = PdfBookmarks()
71+
pdf_bookmarks.upload_document()
72+
pdf_bookmarks.remove_bookmark_by_path()
73+
pdf_bookmarks.download_result()

0 commit comments

Comments
 (0)