Skip to content

Commit f65db05

Browse files
authored
Merge pull request #93 from aspose-pdf-cloud/PDFAPPS-7017-added-use-cases-for-Spliter
PDFAPPS-7017: added use-cases for Spliter
2 parents 0f63d86 + 85cee6c commit f65db05

File tree

2 files changed

+146
-0
lines changed

2 files changed

+146
-0
lines changed

Uses-Cases/Split/splitPages.py

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, SplitResultResponse
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+
16+
class PdfSplitter:
17+
""" Class for managing PDF pages using Aspose PDF Cloud API. """
18+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
19+
self.pdf_api = None
20+
self._init_api(credentials_file)
21+
22+
def _init_api(self, credentials_file: Path):
23+
""" Initialize the API client. """
24+
try:
25+
with credentials_file.open("r", encoding="utf-8") as file:
26+
credentials = json.load(file)
27+
api_key, app_id = credentials.get("key"), credentials.get("id")
28+
if not api_key or not app_id:
29+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
30+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
31+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
32+
logging.error(f"init_api(): Failed to load credentials: {e}")
33+
34+
def upload_document(self):
35+
""" Upload a PDF document to the Aspose Cloud server. """
36+
if self.pdf_api:
37+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
38+
try:
39+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
40+
logging.info(f"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
41+
except Exception as e:
42+
logging.error(f"upload_document(): Failed to upload file: {e}")
43+
44+
def download_result(self, pageName, pageIndex):
45+
""" Download the processed PDF document page from the Aspose Cloud server. """
46+
if self.pdf_api:
47+
try:
48+
temp_file = self.pdf_api.download_file(pageName)
49+
local_path = Config.LOCAL_FOLDER / f"Page_{pageIndex}_{pageName}"
50+
shutil.move(temp_file, str(local_path))
51+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
52+
except Exception as e:
53+
logging.error(f"download_result(): Failed to download file: {e}")
54+
55+
def split_document_by_pages(self):
56+
""" Split source document by pages """
57+
if self.pdf_api:
58+
try:
59+
response: SplitResultResponse = self.pdf_api.post_split_document(Config.PDF_DOCUMENT_NAME)
60+
61+
if response.code == 200:
62+
i = 0
63+
for a_doc in response.result.documents:
64+
self.download_result(a_doc.href, i)
65+
i = i + 1
66+
except Exception as e:
67+
logging.error(f"split_document_by_pages(): Failed in the PdfSplitter: {e}")
68+
69+
if __name__ == "__main__":
70+
pdf_splitter = PdfSplitter()
71+
pdf_splitter.upload_document()
72+
pdf_splitter.split_document_by_pages()

Uses-Cases/Split/splitRanges.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, SplitRangePdfOptions, PageRange, SplitResultResponse
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+
16+
spltRanges: SplitRangePdfOptions = SplitRangePdfOptions([PageRange(1,3), PageRange(4,7)])
17+
18+
class PdfSplitter:
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, pageName, pageIndex):
47+
""" Download the processed PDF document page from the Aspose Cloud server. """
48+
if self.pdf_api:
49+
try:
50+
temp_file = self.pdf_api.download_file(pageName)
51+
local_path = Config.LOCAL_FOLDER / f"Page_{pageIndex}_{pageName}"
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 split_document_by_ranges(self):
58+
""" Split source document by ranges """
59+
if self.pdf_api:
60+
try:
61+
response: SplitResultResponse = self.pdf_api.post_split_range_pdf_document(Config.PDF_DOCUMENT_NAME, spltRanges)
62+
63+
if response.code == 200:
64+
i = 0
65+
for a_doc in response.result.documents:
66+
self.download_result(a_doc.href, i)
67+
i = i + 1
68+
except Exception as e:
69+
logging.error(f"split_document_by_pages(): Failed in the PdfSplitter: {e}")
70+
71+
if __name__ == "__main__":
72+
pdf_splitter = PdfSplitter()
73+
pdf_splitter.upload_document()
74+
pdf_splitter.split_document_by_ranges()

0 commit comments

Comments
 (0)