Skip to content

Commit 325baec

Browse files
authored
Merge pull request #88 from aspose-pdf-cloud/pdfapps-6715-added-use-cases-for-tables
PDFAPPS-6715: added use cases for Tables
2 parents 94a71a3 + c5b4e90 commit 325baec

File tree

4 files changed

+468
-0
lines changed

4 files changed

+468
-0
lines changed

Uses-Cases/Tables/add/appendTable.py

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, Table, Row, Cell, FontStyles, GraphInfo, TextRect, TextState, Color, BorderInfo
6+
# Configure logging
7+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
8+
9+
class Config:
10+
"""Configuration parameters."""
11+
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
12+
LOCAL_FOLDER = Path(r"C:\Samples")
13+
PDF_DOCUMENT_NAME = "sample.pdf"
14+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
15+
PAGE_NUMBER = 2
16+
17+
class PdfTables:
18+
""" Class for managing PDF tables using Aspose PDF Cloud API. """
19+
def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE):
20+
self.pdf_api = None
21+
self._init_api(credentials_file)
22+
23+
def _init_api(self, credentials_file: Path):
24+
""" Initialize the API client. """
25+
try:
26+
with credentials_file.open("r", encoding="utf-8") as file:
27+
credentials = json.load(file)
28+
api_key, app_id = credentials.get("key"), credentials.get("id")
29+
if not api_key or not app_id:
30+
raise ValueError("init_api(): Error: Missing API keys in the credentials file.")
31+
self.pdf_api = PdfApi(ApiClient(api_key, app_id))
32+
except (FileNotFoundError, json.JSONDecodeError, ValueError) as e:
33+
logging.error(f"init_api(): Failed to load credentials: {e}")
34+
35+
def upload_document(self):
36+
""" Upload a PDF document to the Aspose Cloud server. """
37+
if self.pdf_api:
38+
file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
39+
try:
40+
self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path))
41+
logging.info(f"upload_document(): File {Config.PDF_DOCUMENT_NAME} uploaded successfully.")
42+
except Exception as e:
43+
logging.error(f"upload_document(): Failed to upload file: {e}")
44+
45+
def download_result(self):
46+
""" Download the processed PDF document from the Aspose Cloud server. """
47+
if self.pdf_api:
48+
try:
49+
temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME)
50+
local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
51+
shutil.move(temp_file, str(local_path))
52+
logging.info(f"download_result(): File successfully downloaded: {local_path}")
53+
except Exception as e:
54+
logging.error(f"download_result(): Failed to download file: {e}")
55+
56+
def _init_table (self):
57+
""" Initialize new table """
58+
num_of_cols = 5
59+
num_of_rows = 5
60+
61+
header_text_state = TextState(
62+
font = "Arial Bold",
63+
font_size = 11,
64+
foreground_color = Color( a = 255, r = 255, g = 255, b = 255 ),
65+
font_style = FontStyles.BOLD,
66+
)
67+
68+
common_text_state = TextState (
69+
font = "Arial Bold",
70+
font_size = 11,
71+
foreground_color = Color( a=255, r = 112, g = 112, b = 112 ),
72+
font_style=FontStyles.REGULAR
73+
)
74+
75+
col_widths = ""
76+
for col_index in range(0,num_of_cols):
77+
col_widths += " 70"
78+
79+
table_rows = [];
80+
81+
border_table_border = GraphInfo(
82+
color = Color(a = 255, r = 0, g = 255, b = 0 ),
83+
line_width = 0.5
84+
)
85+
86+
for row_index in range(0, num_of_rows):
87+
row_cells = []
88+
89+
for col_index in range(0, num_of_cols):
90+
cell = Cell( default_cell_text_state = common_text_state)
91+
92+
if row_index == 0: # header cells
93+
cell.background_color = Color(a = 255, r = 128, g = 128, b=128)
94+
cell.default_cell_text_state = header_text_state
95+
else:
96+
cell.background_color = Color(a =255, r =255, g =255, b =255)
97+
98+
text_rect = TextRect()
99+
if row_index == 0:
100+
text_rect.text = f"header #{col_index}"
101+
else:
102+
text_rect.text = f"value '({row_index},{col_index})'"
103+
cell.paragraphs = [ text_rect]
104+
105+
row_cells.append(cell)
106+
107+
row = Row(cells=row_cells)
108+
109+
table_rows.append(row)
110+
111+
table = Table(left=150,top=250, column_widths=col_widths, rows=table_rows)
112+
113+
table.default_cell_border = BorderInfo(
114+
top = border_table_border,
115+
right = border_table_border,
116+
bottom = border_table_border,
117+
left = border_table_border,
118+
rounded_border_radius = 2
119+
)
120+
121+
return table
122+
123+
def add_table_on_page (self):
124+
""" Append table to the PDF document page. """
125+
if self.pdf_api:
126+
try:
127+
new_table = self._init_table()
128+
129+
resultTabs = self.pdf_api.post_page_tables( Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER, [ new_table ])
130+
131+
if resultTabs.code == 200:
132+
logging.info(f"add_table_on_page(): Table was appended to the document '{Config.PDF_DOCUMENT_NAME}' on page #'{Config.PAGE_NUMBER}'.")
133+
else:
134+
logging.error(f"add_table_on_page(): Failed to add new table to the document '{Config.PDF_DOCUMENT_NAME}'.")
135+
except Exception as e:
136+
logging.error(f"add_table_on_page(): Failed to append table: {e}")
137+
138+
if __name__ == "__main__":
139+
pdf_tables = PdfTables()
140+
pdf_tables.upload_document()
141+
pdf_tables.add_table_on_page()
142+
pdf_tables.download_result()
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, Table, Row, Cell, FontStyles, GraphInfo, TextRect, TextState, Color, BorderInfo
6+
# Configure logging
7+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
8+
9+
class Config:
10+
"""Configuration parameters."""
11+
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
12+
LOCAL_FOLDER = Path(r"C:\Samples")
13+
PDF_DOCUMENT_NAME = "sample.pdf"
14+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
15+
PAGE_NUMBER = 2
16+
TABLE_ID = "GE5TCOZSGAYCYNRQGUWDINZVFQ3DGMA"
17+
18+
class PdfTables:
19+
""" Class for managing PDF tables 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 _show_tables_info(self, tables, prefix):
47+
if tables and len(tables) > 0 :
48+
for table in tables:
49+
logging.info(f"{prefix} => id: '{table.id}', page: '{table.page_num}', rows: '{len(table.row_list)}', columns: '{len(table.row_list[0].cell_list)}'")
50+
else:
51+
logging.error(f"showBoormarks() error: array of tables is empty!")
52+
53+
def get_all_tables(self):
54+
if self.pdf_api:
55+
resultTabs = self.pdf_api.get_document_tables(Config.PDF_DOCUMENT_NAME)
56+
57+
if resultTabs.code == 200 and resultTabs.tables:
58+
if not resultTabs.tables.list or len(resultTabs.tables.list) == 0:
59+
logging.error("get_all_tables(): Unexpected error - tables is null or empty!!!")
60+
self._show_tables_info(resultTabs.tables.list, "All tables")
61+
return resultTabs.tables.list
62+
else:
63+
logging.error("get_all_tables(): Unexpected error - can't get links!!!")
64+
65+
def get_table_by_id (self):
66+
if self.pdf_api:
67+
resultTabs =self.pdf_api.get_table(Config.PDF_DOCUMENT_NAME, Config.TABLE_ID)
68+
69+
if resultTabs.code == 200 and resultTabs.table:
70+
self._show_tables_info( [ resultTabs.table ], "Table by Id")
71+
return resultTabs.table
72+
else:
73+
logging.error("get_table_by_id(): Unexpected error - can't get links!!!")
74+
75+
if __name__ == "__main__":
76+
pdf_tables = PdfTables()
77+
pdf_tables.upload_document()
78+
pdf_tables.get_all_tables()
79+
pdf_tables.get_table_by_id()
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import shutil
2+
import json
3+
import logging
4+
from pathlib import Path
5+
from asposepdfcloud import ApiClient, PdfApi, Table, Row, Cell, FontStyles, GraphInfo, TextRect, TextState, Color, BorderInfo
6+
# Configure logging
7+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
8+
9+
class Config:
10+
"""Configuration parameters."""
11+
CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json")
12+
LOCAL_FOLDER = Path(r"C:\Samples")
13+
PDF_DOCUMENT_NAME = "sample.pdf"
14+
LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf"
15+
PAGE_NUMBER = 1
16+
TABLE_ID = "GE5TCOZSGAYCYNRQGUWDINZVFQ3DGMA"
17+
18+
class PdfTables:
19+
""" Class for managing PDF tables 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+
58+
def _show_tables_info(self, tables, prefix):
59+
if tables and len(tables) > 0 :
60+
for table in tables:
61+
logging.info(f"{prefix} => id: '{table.id}', page: '{table.page_num}', rows: '{len(table.row_list)}', columns: '{len(table.row_list[0].cell_list)}'")
62+
else:
63+
logging.error(f"_show_tables_info() error: array of tables is empty!")
64+
65+
def get_all_tables(self, prefix):
66+
if self.pdf_api:
67+
resultTabs = self.pdf_api.get_document_tables(Config.PDF_DOCUMENT_NAME)
68+
69+
if resultTabs.code == 200 and resultTabs.tables:
70+
if not resultTabs.tables.list or len(resultTabs.tables.list) == 0:
71+
logging.error("get_all_tables(): Unexpected error - tables is null or empty!!!")
72+
self._show_tables_info(resultTabs.tables.list, prefix)
73+
else:
74+
logging.error("get_all_tables(): Unexpected error - can't get links!!!")
75+
76+
def delete_table(self):
77+
if self.pdf_api:
78+
resultTabs = self.pdf_api.delete_table(Config.PDF_DOCUMENT_NAME, Config.TABLE_ID)
79+
if resultTabs.code == 200:
80+
logging.info(f"delete_table(): Table #{Config.TABLE_ID} deleted!")
81+
else:
82+
logging.error("delete_table(): Unexpected error - can't delete table!")
83+
84+
def delete_tables(self):
85+
if self.pdf_api:
86+
resultTabs = self.pdf_api.delete_page_tables(Config.PDF_DOCUMENT_NAME, Config.PAGE_NUMBER)
87+
88+
if resultTabs.code == 200:
89+
logging.info(f"delete_tables(): Tables on page #{Config.PAGE_NUMBER} deleted!")
90+
else:
91+
logging.error("delete_tables(): Unexpected error - can't get tables!!!")
92+
93+
if __name__ == "__main__":
94+
pdf_tables = PdfTables()
95+
pdf_tables.upload_document()
96+
97+
pdf_tables.get_all_tables("All tables")
98+
pdf_tables.delete_table()
99+
pdf_tables.get_all_tables("Tables after drop one")
100+
101+
pdf_tables.delete_tables()
102+
pdf_tables.get_all_tables("Tables after drop all")
103+
104+
pdf_tables.download_result()

0 commit comments

Comments
 (0)