|
| 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() |
0 commit comments