Skip to content

Commit e25ea86

Browse files
authored
Merge pull request #81 from aspose-pdf-cloud/pdfapps-6709-added-use-cases-for-links
PDFAPPS-6709: added use cases for Links
2 parents ab69362 + 219ef85 commit e25ea86

File tree

4 files changed

+372
-0
lines changed

4 files changed

+372
-0
lines changed

Uses-Cases/Links/add/appendLink.py

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, LinkAnnotation, LinkActionType, LinkHighlightingMode, Color, Link, Rectangle
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_LINK_ACTION = "https://reference.aspose.cloud/pdf/"
18+
PAGE_NUMBER = 2
19+
LINK_RECT = Rectangle(llx=244.914, lly=488.622, urx=284.776, ury=498.588)
20+
21+
22+
class PdfLinks:
23+
"""Class for managing PDF links using Aspose PDF Cloud API."""
24+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
25+
self.pdf_api = None
26+
self._init_api(credentials_file)
27+
28+
def _init_api(self, credentials_file: Path):
29+
"""Initialize the API client."""
30+
try:
31+
with credentials_file.open("r", encoding="utf-8") as file:
32+
credentials = json.load(file)
33+
api_key, app_id = credentials.get("key"), credentials.get("id")
34+
if not api_key or not app_id:
35+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
36+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
37+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
38+
logging.error(f"init_api(): Failed to load credentials: {e}")
39+
40+
def upload_document(self):
41+
"""Upload a PDF document to the Aspose Cloud server."""
42+
if self.pdf_api:
43+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
44+
try:
45+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
46+
logging.info(f"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
47+
except Exception as e:
48+
logging.error(f"upload_document(): Failed to upload file: {e}")
49+
50+
def download_result(self):
51+
"""Download the processed PDF document from the Aspose Cloud server."""
52+
if self.pdf_api:
53+
try:
54+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
55+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
56+
shutil.move(temp_file, str(local_path))
57+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
58+
except Exception as e:
59+
logging.error(f"download_result(): Failed to download file: {e}")
60+
61+
def append_link(self):
62+
"""Append a new hyperlink annotation to a specific page in the PDF document."""
63+
if self.pdf_api:
64+
link_annotation = LinkAnnotation(
65+
links=[Link(href=Config.NEW_LINK_ACTION)],
66+
action_type= LinkActionType.GOTOURIACTION,
67+
action=Config.NEW_LINK_ACTION,
68+
highlighting=LinkHighlightingMode.INVERT,
69+
color=Color(a=255, r=0, g=255, b=0),
70+
rect=Config.LINK_RECT,
71+
)
72+
73+
try:
74+
response = self.pdf_api.post_page_link_annotations(
75+
Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER, [link_annotation]
76+
)
77+
if response.code == 200:
78+
logging.info(f"append_link(): Link '{Config.NEW_LINK_ACTION}' added to page #{Config.PAGE_NUMBER}.")
79+
else:
80+
logging.error(f"append_link(): Failed to add link to the page. Response code: {response.code}")
81+
except Exception as e:
82+
logging.error(f"append_link(): Error while adding link: {e}")
83+
84+
85+
if __name__ == "__main__":
86+
pdf_links = PdfLinks()
87+
pdf_links.upload_document()
88+
pdf_links.append_link()
89+
pdf_links.download_result()
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi
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+
PAGE_NUMBER = 2
18+
LINK_FIND_ID = "GI5UO32UN5KVESKBMN2GS33OHMZTEMJMGUYDQLBTGYYCYNJSGE"
19+
20+
21+
class PdfLinks:
22+
"""Class for managing PDF links using Aspose PDF Cloud API."""
23+
24+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
25+
self.pdf_api = None
26+
self._init_api(credentials_file)
27+
28+
def _init_api(self, credentials_file: Path):
29+
"""Initialize the API client."""
30+
try:
31+
with credentials_file.open("r", encoding="utf-8") as file:
32+
credentials = json.load(file)
33+
api_key, app_id = credentials.get("key"), credentials.get("id")
34+
if not api_key or not app_id:
35+
raise ValueError("Error: Missing API keys in the credentials file.")
36+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
37+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
38+
logging.error(f"Failed to load credentials: {e}")
39+
40+
def upload_document(self):
41+
"""Upload a PDF document to the Aspose Cloud server."""
42+
if self.pdf_api:
43+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
44+
try:
45+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
46+
logging.info(f"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
47+
except Exception as e:
48+
logging.error(f"Failed to upload file: {e}")
49+
50+
def show_links_array(self, links, prefix):
51+
for item in links:
52+
logging.info(f"{prefix} Link ID: '{item.id}' - Link Action: '{item.action}'")
53+
54+
def get_all_links(self):
55+
"""Get all hyperlink annotations for a specific PDF document."""
56+
if self.pdf_api:
57+
try:
58+
response = self.pdf_api.get_page_link_annotations( Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER)
59+
if response.code == 200:
60+
self.show_links_array(response.links.list, "All: ")
61+
else:
62+
logging.error(f"Failed to add link to the page. Response code: {response.code}")
63+
except Exception as e:
64+
logging.error(f"Error while adding link: {e}")
65+
66+
def get_link_by_id(self, link_id: str):
67+
"""Get hyperlink annotation using the specific Id in PDF document."""
68+
if self.pdf_api:
69+
try:
70+
result_link = self.pdf_api.get_link_annotation(Config.PDF_DOCUMENT_NAME, link_id)
71+
if result_link.code == 200:
72+
self.show_links_array([result_link.link], "Find: ")
73+
except Exception as e:
74+
logging.error(f"Error while adding link: {e}")
75+
76+
if __name__ == "__main__":
77+
pdf_links = PdfLinks()
78+
pdf_links.upload_document()
79+
pdf_links.get_all_links()
80+
pdf_links.get_link_by_id(Config.LINK_FIND_ID)

Uses-Cases/Links/remove/removeLink.py

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
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+
PAGE_NUMBER = 2
18+
LINK_FIND_ID = "GI5UO32UN5KVESKBMN2GS33OHMZTEMJMGUYDQLBTGYYCYNJSGE"
19+
20+
21+
class PdfLinks:
22+
"""Class for managing PDF links using Aspose PDF Cloud API."""
23+
24+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
25+
self.pdf_api = None
26+
self._init_api(credentials_file)
27+
28+
def _init_api(self, credentials_file: Path):
29+
"""Initialize the API client."""
30+
try:
31+
with credentials_file.open("r", encoding="utf-8") as file:
32+
credentials = json.load(file)
33+
api_key, app_id = credentials.get("key"), credentials.get("id")
34+
if not api_key or not app_id:
35+
raise ValueError("Error: Missing API keys in the credentials file.")
36+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
37+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
38+
logging.error(f"Failed to load credentials: {e}")
39+
40+
def upload_document(self):
41+
"""Upload a PDF document to the Aspose Cloud server."""
42+
if self.pdf_api:
43+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
44+
try:
45+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
46+
logging.info(f"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
47+
except Exception as e:
48+
logging.error(f"Failed to upload file: {e}")
49+
50+
def download_result(self):
51+
"""Download the processed PDF document from the Aspose Cloud server."""
52+
if self.pdf_api:
53+
try:
54+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
55+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
56+
shutil.move(temp_file, str(local_path))
57+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
58+
except Exception as e:
59+
logging.error(f"download_result(): Failed to download file: {e}")
60+
61+
def show_links_array(self, links, prefix):
62+
for item in links:
63+
logging.info(f"{prefix} Link ID: '{item.id}' - Link Action: '{item.action}'")
64+
65+
def get_all_links(self):
66+
"""Get all hyperlink annotations for a specific PDF document."""
67+
if self.pdf_api:
68+
try:
69+
response = self.pdf_api.get_page_link_annotations( Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER)
70+
if response.code == 200:
71+
self.show_links_array(response.links.list, "All: ")
72+
else:
73+
logging.error(f"Failed to add link to the page. Response code: {response.code}")
74+
except Exception as e:
75+
logging.error(f"Error while adding link: No links found - {e}")
76+
77+
def remove_link_by_id(self):
78+
if self.pdf_api:
79+
response: AsposeResponse = self.pdf_api.delete_link_annotation(Config.PDF_DOCUMENT_NAME, Config.LINK_FIND_ID)
80+
81+
if response.code == 200:
82+
logging.info("Link annotation with ID " + Config.LINK_FIND_ID + " has been removed.")
83+
else:
84+
logging.erro("Failed to remove link annotation with ID " + Config.LINK_FIND_ID)
85+
86+
if __name__ == "__main__":
87+
pdf_links = PdfLinks()
88+
pdf_links.upload_document()
89+
pdf_links.get_all_links()
90+
pdf_links.remove_link_by_id()
91+
pdf_links.download_result()
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, LinkAnnotationsResponse, LinkAnnotationResponse
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_LINK_ACTION = "https://reference.aspose.cloud/pdf/"
14+
PAGE_NUMBER = 2
15+
LINK_FIND_ID = "GI5UO32UN5KVESKBMN2GS33OHMZTEMJMGUYDQLBTGYYCYNJSGE"
16+
17+
# Configure logging
18+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
19+
20+
class PdfLinks:
21+
"""Class for managing PDF links 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_links_array(self, links, prefix):
61+
"""Show all hyperlink annotations for a specific PDF document."""
62+
for item in links:
63+
logging.info(f"{prefix} Link ID: '{item.id}' - Link Action: '{item.action}'")
64+
65+
def get_all_links(self):
66+
"""Get all hyperlink annotations for a specific PDF document."""
67+
if self.pdf_api:
68+
try:
69+
response = self.pdf_api.get_page_link_annotations( Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER)
70+
if response.code == 200:
71+
self.show_links_array(response.links.list, "All: ")
72+
else:
73+
logging.error(f"Failed to add link to the page. Response code: {response.code}")
74+
except Exception as e:
75+
logging.error(f"Error while adding link: No links found - {e}")
76+
77+
def get_link_by_id(self) -> LinkAnnotationResponse:
78+
if self.pdf_api:
79+
result_link: LinkAnnotationResponse = self.pdf_api.get_link_annotation(Config.PDF_DOCUMENT_NAME, Config.LINK_FIND_ID)
80+
81+
if result_link.code == 200:
82+
return result_link
83+
84+
print("Link not found.")
85+
return None
86+
87+
def replace_link(self):
88+
if self.pdf_api:
89+
link_annotation: LinkAnnotationResponse = self.get_link_by_id()
90+
91+
if not link_annotation:
92+
return
93+
94+
link_annotation.link.action = Config.NEW_LINK_ACTION
95+
96+
response: LinkAnnotationsResponse = self.pdf_api.put_link_annotation(
97+
Config.PDF_DOCUMENT_NAME,
98+
Config.LINK_FIND_ID,
99+
link_annotation.link,
100+
)
101+
102+
if response.code == 200:
103+
print("Link annotation replaced successfully.")
104+
else:
105+
print("Failed to replace link annotation.")
106+
107+
if __name__ == "__main__":
108+
pdf_links = PdfLinks()
109+
pdf_links.upload_document()
110+
pdf_links.get_all_links()
111+
pdf_links.replace_link()
112+
pdf_links.download_result()

0 commit comments

Comments
 (0)