Skip to content

Commit 88949f5

Browse files
PDFAPPS-6682: added use cases for Headers/Footers
1 parent 2e97e76 commit 88949f5

File tree

4 files changed

+523
-0
lines changed

4 files changed

+523
-0
lines changed
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, ImageFooter, HorizontalAlignment
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_FOOTER_FILE = "sample.png"
17+
PAGE_NUMBER = 2 # Your document page number...
18+
19+
20+
class pdfHederFooter:
21+
"""Class for managing PDF headers and footers 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_file(self, fileName: str):
46+
""" Upload a local fileName to the Aspose Cloud server. """
47+
if not self._ensure_api_initialized():
48+
return
49+
50+
file_path = Config.LOCAL_FOLDER / fileName
51+
try:
52+
self.pdf_api.upload_file(fileName, str(file_path))
53+
logging.info(f"upload_file(): File '{fileName}' uploaded successfully.")
54+
except Exception as e:
55+
logging.error(f"upload_document(): Failed to upload file: {e}")
56+
57+
def upload_document(self):
58+
""" Upload a PDF document to the Aspose Cloud server. """
59+
self.upload_file(Config.PDF_DOCUMENT_NAME)
60+
61+
def download_result(self):
62+
""" Download the processed PDF document from the Aspose Cloud server. """
63+
if not self._ensure_api_initialized():
64+
return
65+
66+
try:
67+
file_path = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
68+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
69+
shutil.move(file_path, str(local_path))
70+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
71+
except Exception as e:
72+
logging.error(f"download_result(): Failed to download file: {e}")
73+
74+
def append_image_footer(self):
75+
"""Append a new image footer to the PDF document."""
76+
if not self._ensure_api_initialized():
77+
return
78+
79+
new_footer = ImageFooter(
80+
background = True,
81+
horizontal_alignment = HorizontalAlignment.CENTER,
82+
file_name = Config.IMAGE_FOOTER_FILE,
83+
width = 24,
84+
height = 24
85+
)
86+
87+
try:
88+
response = self.pdf_api.post_document_image_footer(
89+
Config.PDF_DOCUMENT_NAME, new_footer
90+
)
91+
if response.code == 200:
92+
logging.info(f"append_image_footer(): Footer '{new_footer.file_name}' added to the document #{Config.PDF_DOCUMENT_NAME}.")
93+
else:
94+
logging.error(f"append_image_footer(): Failed to add footer '{new_footer.file_name}' to the document #{Config.PDF_DOCUMENT_NAME}. Response code: {response.code}")
95+
except Exception as e:
96+
logging.error(f"append_image_footer(): Error while adding footer: {e}")
97+
98+
def append_image_footer_page(self):
99+
"""Append a new image footer on the page in PDF document."""
100+
if not self._ensure_api_initialized():
101+
return
102+
103+
new_footer = ImageFooter(
104+
background = True,
105+
horizontal_alignment = HorizontalAlignment.RIGHT,
106+
file_name = Config.IMAGE_FOOTER_FILE,
107+
width = 24,
108+
height = 24
109+
)
110+
111+
try:
112+
response = self.pdf_api.post_document_image_footer(
113+
Config.PDF_DOCUMENT_NAME, new_footer, start_page_number=Config.PAGE_NUMBER, end_page_number=Config.PAGE_NUMBER
114+
)
115+
if response.code == 200:
116+
logging.info(f"append_image_footer_page(): Footer '{new_footer.file_name}' added to the page #{Config.PAGE_NUMBER}.")
117+
else:
118+
logging.error(f"append_image_footer_page(): Failed to add footer '{new_footer.file_name}' to the document #{Config.PAGE_NUMBER}. Response code: {response.code}")
119+
except Exception as e:
120+
logging.error(f"append_image_footer_page(): Error while adding footer: {e}")
121+
122+
123+
if __name__ == "__main__":
124+
pdf_header_footer = pdfHederFooter()
125+
pdf_header_footer.upload_document()
126+
pdf_header_footer.upload_file(Config.IMAGE_FOOTER_FILE)
127+
pdf_header_footer.append_image_footer()
128+
pdf_header_footer.append_image_footer_page()
129+
pdf_header_footer.download_result()
Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, ImageHeader, HorizontalAlignment, TextHorizontalAlignment
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_HEADER_FILE = "sample.png"
17+
PAGE_NUMBER = 2 # Your document page number...
18+
19+
20+
class pdfHederFooter:
21+
"""Class for managing PDF headers and footers 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_file(self, fileName: str):
46+
""" Upload a local fileName to the Aspose Cloud server. """
47+
if not self._ensure_api_initialized():
48+
return
49+
50+
file_path = Config.LOCAL_FOLDER / fileName
51+
try:
52+
self.pdf_api.upload_file(fileName, str(file_path))
53+
logging.info(f"upload_file(): File '{fileName}' uploaded successfully.")
54+
except Exception as e:
55+
logging.error(f"upload_document(): Failed to upload file: {e}")
56+
57+
def upload_document(self):
58+
""" Upload a PDF document to the Aspose Cloud server. """
59+
self.upload_file(Config.PDF_DOCUMENT_NAME)
60+
61+
def download_result(self):
62+
""" Download the processed PDF document from the Aspose Cloud server. """
63+
if not self._ensure_api_initialized():
64+
return
65+
66+
try:
67+
file_path = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
68+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
69+
shutil.move(file_path, str(local_path))
70+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
71+
except Exception as e:
72+
logging.error(f"download_result(): Failed to download file: {e}")
73+
74+
def append_image_header(self):
75+
"""Append a new image header to the PDF document."""
76+
if not self._ensure_api_initialized():
77+
return
78+
79+
new_header = ImageHeader(
80+
background = True,
81+
horizontal_alignment = HorizontalAlignment.CENTER,
82+
file_name = Config.IMAGE_HEADER_FILE,
83+
width = 24,
84+
height = 24
85+
)
86+
87+
try:
88+
response = self.pdf_api.post_document_image_header(
89+
Config.PDF_DOCUMENT_NAME, new_header
90+
)
91+
if response.code == 200:
92+
logging.info(f"append_image_header(): Header '{new_header.file_name}' added to the document '{Config.PDF_DOCUMENT_NAME}'.")
93+
else:
94+
logging.error(f"append_image_header(): Failed to add header '{new_header.file_name}' to the document '{Config.PDF_DOCUMENT_NAME}'. Response code: {response.code}")
95+
except Exception as e:
96+
logging.error(f"append_image_header(): Error while adding header: {e}")
97+
98+
def append_image_heade_page(self):
99+
"""Append a new image header to the page on PDF document."""
100+
if not self._ensure_api_initialized():
101+
return
102+
103+
new_header = ImageHeader(
104+
background = True,
105+
horizontal_alignment = HorizontalAlignment.LEFT,
106+
file_name = Config.IMAGE_HEADER_FILE,
107+
width = 24,
108+
height = 24
109+
)
110+
111+
try:
112+
response = self.pdf_api.post_document_image_header(
113+
Config.PDF_DOCUMENT_NAME, new_header, start_page_number=Config.PAGE_NUMBER, end_page_number=Config.PAGE_NUMBER
114+
)
115+
if response.code == 200:
116+
logging.info(f"append_image_heade_page(): Header '{new_header.file_name}' added to the page #{Config.PAGE_NUMBER}.")
117+
else:
118+
logging.error(f"append_image_heade_page(): Failed to add header '{new_header.file_name}' to the page #{Config.PAGE_NUMBER}. Response code: {response.code}")
119+
except Exception as e:
120+
logging.error(f"append_image_heade_page(): Error while adding header: {e}")
121+
122+
123+
if __name__ == "__main__":
124+
pdf_header_footer = pdfHederFooter()
125+
pdf_header_footer.upload_document()
126+
pdf_header_footer.upload_file(Config.IMAGE_HEADER_FILE)
127+
pdf_header_footer.append_image_header()
128+
pdf_header_footer.append_image_heade_page()
129+
pdf_header_footer.download_result()

0 commit comments

Comments
 (0)