Skip to content

Commit 6f16ca2

Browse files
authored
Merge pull request #83 from aspose-pdf-cloud/pdfapps-6714-added-use-cases-for-stamps
PDFAPPS-6714: added use cases for Stamps
2 parents 19f8657 + dc69444 commit 6f16ca2

File tree

2 files changed

+211
-0
lines changed

2 files changed

+211
-0
lines changed

Uses-Cases/Stamps/add/appendStamps.py

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, Stamp, AsposeResponse, HorizontalAlignment, StampType
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+
IMAGE_STAMP_FILE ="sample.png"
17+
PAGE_NUMBER = 2
18+
STAMP_TEXT = "NEW TEXT STAMP"
19+
IMAGE_STAMP_LLY = 800
20+
IMAGE_STAMP_WIDTH = 24
21+
IMAGE_STAMP_HEIGHT = 24
22+
23+
class PdfStamps:
24+
""" Class for managing PDF stamps 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_file(self, fileName: str):
49+
""" Upload a local fileName to the Aspose Cloud server. """
50+
if not self._ensure_api_initialized():
51+
return
52+
53+
file_path = Config.LOCAL_FOLDER / fileName
54+
try:
55+
self.pdf_api.upload_file(fileName, str(file_path))
56+
logging.info(f"upload_file(): File '{fileName}' uploaded successfully.")
57+
except Exception as e:
58+
logging.error(f"upload_document(): Failed to upload file: {e}")
59+
60+
def upload_document(self):
61+
""" Upload a PDF document to the Aspose Cloud server. """
62+
self.upload_file(Config.PDF_DOCUMENT_NAME)
63+
64+
def download_result(self):
65+
""" Download the processed PDF document from the Aspose Cloud server. """
66+
if not self._ensure_api_initialized():
67+
return
68+
69+
try:
70+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
71+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
72+
shutil.move(temp_file, str(local_path))
73+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
74+
except Exception as e:
75+
logging.error(f"download_result(): Failed to download file: {e}")
76+
77+
def add_document_stamps(self):
78+
""" Adds a text stamp to a specific page in a PDF document. """
79+
80+
text_stamp: Stamp = Stamp(
81+
type = StampType.TEXT,
82+
background = True,
83+
horizontal_alignment = HorizontalAlignment.CENTER,
84+
text_alignment = HorizontalAlignment.CENTER,
85+
value=Config.STAMP_TEXT
86+
)
87+
88+
image_stamp: Stamp = Stamp(
89+
type = StampType.IMAGE,
90+
background = True,
91+
horizontal_alignment = HorizontalAlignment.CENTER,
92+
text_alignment = HorizontalAlignment.CENTER,
93+
value = "NEW IMAGE STAMP",
94+
file_name = Config.IMAGE_STAMP_FILE,
95+
y_indent = Config.IMAGE_STAMP_LLY,
96+
width = Config.IMAGE_STAMP_WIDTH,
97+
height = Config.IMAGE_STAMP_HEIGHT
98+
)
99+
100+
responseTextStamp: AsposeResponse = self.pdf_api.post_document_text_stamps(Config.PDF_DOCUMENT_NAME, [ text_stamp ])
101+
responseImageStamp: AsposeResponse = self.pdf_api.post_document_image_stamps(Config.PDF_DOCUMENT_NAME, [ image_stamp ])
102+
103+
if responseTextStamp.code == 200 and responseImageStamp.code == 200:
104+
logging.info(f"Text stamp '{Config.STAMP_TEXT}' and image stamp '{Config.IMAGE_STAMP_FILE}' added to the document '{Config.PDF_DOCUMENT_NAME}'.")
105+
else:
106+
if responseTextStamp.code != 200:
107+
logging.error(f"Failed to add text stamp '{Config.STAMP_TEXT}' to the document '{Config.PDF_DOCUMENT_NAME}'.")
108+
else:
109+
logging.error(f"Failed to add image stamp '{Config.IMAGE_STAMP_FILE}' to the document '{Config.PDF_DOCUMENT_NAME}'.")
110+
111+
if __name__ == "__main__":
112+
pdf_stamps = PdfStamps()
113+
pdf_stamps.upload_document()
114+
pdf_stamps.upload_file(Config.IMAGE_STAMP_FILE)
115+
pdf_stamps.add_document_stamps()
116+
pdf_stamps.download_result()
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, Stamp, AsposeResponse
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 = "pdf_stamps.pdf"
15+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
16+
IMAGE_STAMP_FILE ="sample.png"
17+
PAGE_NUMBER = 2
18+
STAMP_ID = "GE5TCOZQ"
19+
20+
class PdfStamps:
21+
""" Class for managing PDF stamps using Aspose PDF Cloud API. """
22+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
23+
self.pdf_api = None
24+
self._init_api(credentials_file)
25+
26+
def _init_api(self, credentials_file: Path):
27+
""" Initialize the API client. """
28+
try:
29+
with credentials_file.open("r", encoding="utf-8") as file:
30+
credentials = json.load(file)
31+
api_key, app_id = credentials.get("key"), credentials.get("id")
32+
if not api_key or not app_id:
33+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
34+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
35+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
36+
logging.error(f"init_api(): Failed to load credentials: {e}")
37+
38+
def _ensure_api_initialized(self):
39+
""" Check if the API is initialized before making API calls. """
40+
if not self.pdf_api:
41+
logging.error("ensure_api_initialized(): PDF API is not initialized. Operation aborted.")
42+
return False
43+
return True
44+
45+
def upload_document(self):
46+
""" Upload a PDF document to the Aspose Cloud server. """
47+
if not self._ensure_api_initialized():
48+
return
49+
50+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
51+
try:
52+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
53+
logging.info(f"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
54+
except Exception as e:
55+
logging.error(f"upload_document(): Failed to upload file: {e}")
56+
57+
def download_result(self):
58+
""" Download the processed PDF document from the Aspose Cloud server. """
59+
if not self._ensure_api_initialized():
60+
return
61+
62+
try:
63+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
64+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
65+
shutil.move(temp_file, str(local_path))
66+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
67+
except Exception as e:
68+
logging.error(f"download_result(): Failed to download file: {e}")
69+
70+
def delete_page_stamps(self):
71+
""" Remove stamp in a specific page of the PDF document. """
72+
73+
response: AsposeResponse = self.pdf_api.delete_page_stamps(Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER)
74+
75+
if response.code == 200 :
76+
logging.info(f"Stamps on page #{Config.PAGE_NUMBER} was deleted for the document '{Config.PDF_DOCUMENT_NAME}'.")
77+
else:
78+
logging.error(f"Failed to remove stamps on page #{Config.PAGE_NUMBER} for the document '{Config.PDF_DOCUMENT_NAME}'.")
79+
80+
def delete_stamp_by_id(self):
81+
""" Remove stamp by Id in the PDF document. """
82+
83+
response: AsposeResponse = self.pdf_api.delete_stamp(Config.PDF_DOCUMENT_NAME, Config.STAMP_ID)
84+
85+
if response.code == 200 :
86+
logging.info(f"Stamps with Id '{Config.STAMP_ID}' was deleted for the document '{Config.PDF_DOCUMENT_NAME}'.")
87+
else:
88+
logging.error(f"Failed to remove stamp with Id '{Config.STAMP_ID}' for the document '{Config.PDF_DOCUMENT_NAME}'.")
89+
90+
if __name__ == "__main__":
91+
pdf_stamps = PdfStamps()
92+
pdf_stamps.upload_document()
93+
pdf_stamps.delete_stamp_by_id()
94+
pdf_stamps.delete_page_stamps()
95+
pdf_stamps.download_result()

0 commit comments

Comments
 (0)