Skip to content

Commit 54c60c1

Browse files
authored
Merge pull request #86 from aspose-pdf-cloud/pdfapps-6682-added-use-cases-for-headers-footers
PDFAPPS-6713: added use cases for Headers/Footers
2 parents 02731da + 581a21e commit 54c60c1

File tree

4 files changed

+461
-0
lines changed

4 files changed

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

0 commit comments

Comments
 (0)