Skip to content

Commit 258356a

Browse files
authored
Merge pull request #82 from aspose-pdf-cloud/pdfapps-6710-added-use-cases-for-pages
PDFAPPS-6710: added use cases for Pages
2 parents e25ea86 + f961136 commit 258356a

File tree

6 files changed

+424
-0
lines changed

6 files changed

+424
-0
lines changed

Uses-Cases/Pages/add/appendNewPage.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, DocumentPagesResponse
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+
18+
class PdfPages:
19+
""" Class for managing PDF pages using Aspose PDF Cloud API. """
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("init_api(): 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"init_api(): 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"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
43+
except Exception as e:
44+
logging.error(f"upload_document(): Failed to upload file: {e}")
45+
46+
def download_result(self):
47+
""" Download the processed PDF document from the Aspose Cloud server. """
48+
if self.pdf_api:
49+
try:
50+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
51+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
52+
shutil.move(temp_file, str(local_path))
53+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
54+
except Exception as e:
55+
logging.error(f"download_result(): Failed to download file: {e}")
56+
57+
def add_new_page(self):
58+
""" Add new page to end of the PDF document. """
59+
if self.pdf_api:
60+
result_pages: DocumentPagesResponse = self.pdf_api.put_add_new_page(Config.PDF_DOCUMENT_NAME)
61+
62+
if result_pages.code == 200 and result_pages.pages:
63+
logging.info(f"Added a new page: {result_pages.pages.list[-1]}")
64+
else:
65+
logging.error("Failed to add a new page.")
66+
67+
if __name__ == "__main__":
68+
pdf_pages = PdfPages()
69+
pdf_pages.upload_document()
70+
pdf_pages.add_new_page()
71+
pdf_pages.download_result()
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, DocumentPagesResponse
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.png"
17+
PAGE_NUMBER = 2
18+
19+
class PdfPages:
20+
""" Class for managing PDF pages using Aspose PDF Cloud API. """
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("init_api(): 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"init_api(): 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"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
44+
except Exception as e:
45+
logging.error(f"upload_document(): Failed to upload file: {e}")
46+
47+
def get_page_info(self):
48+
""" Get page information of the PDF document. """
49+
if self.pdf_api:
50+
result_pages: DocumentPagesResponse = self.pdf_api.get_page(Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER)
51+
52+
if result_pages.code == 200:
53+
logging.info(f"Page #{Config.PAGE_NUMBER} information: {result_pages.page}")
54+
else:
55+
logging.error(f"Failed to get the page #{Config.PAGE_NUMBER}.")
56+
57+
def get_page_as_png(self):
58+
""" Get page information of the PDF document. """
59+
if self.pdf_api:
60+
try:
61+
result_pages = self.pdf_api.get_page_convert_to_png(Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER)
62+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
63+
shutil.move(result_pages, str(local_path))
64+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
65+
except Exception as e:
66+
logging.error(f"download_result(): Failed to download file: {e}")
67+
68+
if __name__ == "__main__":
69+
pdf_pages = PdfPages()
70+
pdf_pages.upload_document()
71+
pdf_pages.get_page_info()
72+
pdf_pages.get_page_as_png()
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+
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+
PAGE_NUMBER = 2
17+
18+
class PdfPages:
19+
""" Class for managing PDF pages using Aspose PDF Cloud API. """
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("init_api(): 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"init_api(): 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"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
43+
except Exception as e:
44+
logging.error(f"upload_document(): Failed to upload file: {e}")
45+
46+
def download_result(self):
47+
""" Download the processed PDF document from the Aspose Cloud server. """
48+
if self.pdf_api:
49+
try:
50+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
51+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
52+
shutil.move(temp_file, str(local_path))
53+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
54+
except Exception as e:
55+
logging.error(f"download_result(): Failed to download file: {e}")
56+
57+
def move_page(self):
58+
""" Moves a page to a new location in the PDF document. """
59+
if self.pdf_api:
60+
response: AsposeResponse = self.pdf_api.post_move_page(Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER, Config.PAGE_NUMBER + 1)
61+
62+
if response.code == 200:
63+
logging.info(f"Page #{Config.PAGE_NUMBER} has been moved to position #{Config.PAGE_NUMBER + 1}.")
64+
else:
65+
logging.error("Failed to move a new page.")
66+
67+
if __name__ == "__main__":
68+
pdf_pages = PdfPages()
69+
pdf_pages.upload_document()
70+
pdf_pages.move_page()
71+
pdf_pages.download_result()

Uses-Cases/Pages/remove/removePage.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
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+
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+
PAGE_NUMBER = 2
17+
18+
class PdfPages:
19+
""" Class for managing PDF pages using Aspose PDF Cloud API. """
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("init_api(): 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"init_api(): 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"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
43+
except Exception as e:
44+
logging.error(f"upload_document(): Failed to upload file: {e}")
45+
46+
def download_result(self):
47+
""" Download the processed PDF document from the Aspose Cloud server. """
48+
if self.pdf_api:
49+
try:
50+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
51+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
52+
shutil.move(temp_file, str(local_path))
53+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
54+
except Exception as e:
55+
logging.error(f"download_result(): Failed to download file: {e}")
56+
57+
def delete_page(self):
58+
""" Deletes a specific page from a PDF document. """
59+
if self.pdf_api:
60+
result = self.pdf_api.delete_page(Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER)
61+
if result.code == 200:
62+
logging.info(f"Page #{Config.PAGE_NUMBER} deleted.")
63+
else:
64+
logging.error(f"Failed to delete page #{Config.PAGE_NUMBER}.")
65+
66+
if __name__ == "__main__":
67+
pdf_pages = PdfPages()
68+
pdf_pages.upload_document()
69+
pdf_pages.delete_page()
70+
pdf_pages.download_result()
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
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+
PAGE_NUMBER = 2
17+
STAMP_TEXT = "NEW TEXT STAMP"
18+
19+
class PdfPages:
20+
""" Class for managing PDF pages using Aspose PDF Cloud API. """
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("init_api(): 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"init_api(): 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"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
44+
except Exception as e:
45+
logging.error(f"upload_document(): Failed to upload file: {e}")
46+
47+
def download_result(self):
48+
""" Download the processed PDF document from the Aspose Cloud server. """
49+
if self.pdf_api:
50+
try:
51+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
52+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
53+
shutil.move(temp_file, str(local_path))
54+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
55+
except Exception as e:
56+
logging.error(f"download_result(): Failed to download file: {e}")
57+
58+
def add_page_text_stamp(self):
59+
""" Adds a text stamp to a specific page in a PDF document. """
60+
if self.pdf_api:
61+
page_stamp: Stamp = Stamp(
62+
type = StampType.TEXT,
63+
background = True,
64+
horizontal_alignment = HorizontalAlignment.CENTER,
65+
text_alignment = HorizontalAlignment.CENTER,
66+
value = Config.STAMP_TEXT,
67+
page_index = Config.PAGE_NUMBER,
68+
)
69+
70+
response: AsposeResponse = self.pdf_api.put_page_add_stamp(Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER, page_stamp)
71+
72+
if response.code == 200:
73+
logging.info(f"Text stamp '{Config.STAMP_TEXT}' added to page #{Config.PAGE_NUMBER}.")
74+
else:
75+
logging.error(f"Failed to add text stamp '{Config.STAMP_TEXT}' to page #{Config.PAGE_NUMBER}.")
76+
77+
if __name__ == "__main__":
78+
pdf_pages = PdfPages()
79+
pdf_pages.upload_document()
80+
pdf_pages.add_page_text_stamp()
81+
pdf_pages.download_result()

0 commit comments

Comments
 (0)