|
| 1 | +import shutil |
| 2 | +import json |
| 3 | +import logging |
| 4 | +from pathlib import Path |
| 5 | +from asposepdfcloud import ApiClient, PdfApi, TextReplace, TextReplaceListRequest |
| 6 | + |
| 7 | +class Config: |
| 8 | + """Configuration parameters.""" |
| 9 | + CREDENTIALS_FILE = Path(r"C:\\Projects\\ASPOSE\\Pdf.Cloud\\Credentials\\credentials.json") |
| 10 | + LOCAL_FOLDER = Path(r"C:\\Samples") |
| 11 | + PDF_DOCUMENT_NAME = "sample.pdf" |
| 12 | + LOCAL_RESULT_DOCUMENT_NAME = "output_sample.pdf" |
| 13 | + PAGE_NUMBER = 2 |
| 14 | + TEXT_SOURCE_FOR_REPLACE = "YOUR source text" |
| 15 | + TEXT_NEW_VALUE = "YOUR new text" |
| 16 | + |
| 17 | +# Configure logging |
| 18 | +logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") |
| 19 | + |
| 20 | +class PdfTexts: |
| 21 | + """Class for managing PDF texts using Aspose PDF Cloud API.""" |
| 22 | + |
| 23 | + def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE): |
| 24 | + self.pdf_api = None |
| 25 | + self._init_api(credentials_file) |
| 26 | + |
| 27 | + def _init_api(self, credentials_file: Path): |
| 28 | + """Initialize the API client.""" |
| 29 | + try: |
| 30 | + with credentials_file.open("r", encoding="utf-8") as file: |
| 31 | + credentials = json.load(file) |
| 32 | + api_key, app_id = credentials.get("key"), credentials.get("id") |
| 33 | + if not api_key or not app_id: |
| 34 | + raise ValueError("Error: Missing API keys in the credentials file.") |
| 35 | + self.pdf_api = PdfApi(ApiClient(api_key, app_id)) |
| 36 | + except (FileNotFoundError, json.JSONDecodeError, ValueError) as e: |
| 37 | + logging.error(f"Failed to load credentials: {e}") |
| 38 | + |
| 39 | + def _ensure_api_initialized(self): |
| 40 | + """Check if the API is initialized before making API calls.""" |
| 41 | + if not self.pdf_api: |
| 42 | + logging.error("PDF API is not initialized. Operation aborted.") |
| 43 | + return False |
| 44 | + return True |
| 45 | + |
| 46 | + def upload_document(self): |
| 47 | + """Upload a PDF document to the Aspose Cloud server.""" |
| 48 | + if not self._ensure_api_initialized(): |
| 49 | + return |
| 50 | + |
| 51 | + file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME |
| 52 | + try: |
| 53 | + self.pdf_api.upload_file(Config.PDF_DOCUMENT_NAME, str(file_path)) |
| 54 | + logging.info(f"File {Config.PDF_DOCUMENT_NAME} uploaded successfully.") |
| 55 | + except Exception as e: |
| 56 | + logging.error(f"Failed to upload file: {e}") |
| 57 | + |
| 58 | + def download_result(self): |
| 59 | + """ Download the processed PDF document from the Aspose Cloud server """ |
| 60 | + if not self._ensure_api_initialized(): |
| 61 | + return |
| 62 | + |
| 63 | + try: |
| 64 | + temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME) |
| 65 | + local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME |
| 66 | + shutil.move(temp_file, str(local_path)) |
| 67 | + logging.info(f"download_result(): File successfully downloaded: {local_path}") |
| 68 | + except Exception as e: |
| 69 | + logging.error(f"download_result(): Failed to download file: {e}") |
| 70 | + |
| 71 | + def replace_document_texts(self): |
| 72 | + """ Replace text in the PDF document """ |
| 73 | + if not self.pdf_api: |
| 74 | + return |
| 75 | + |
| 76 | + text_replace_obj = TextReplace(old_value=Config.TEXT_SOURCE_FOR_REPLACE, new_value=Config.TEXT_NEW_VALUE, regex=False) |
| 77 | + |
| 78 | + text_replace_request = TextReplaceListRequest([text_replace_obj]) |
| 79 | + |
| 80 | + response = self.pdf_api.post_document_text_replace( |
| 81 | + Config.PDF_DOCUMENT_NAME, text_replace_request |
| 82 | + ) |
| 83 | + |
| 84 | + if response.code == 200: |
| 85 | + print(f"Text '{Config.TEXT_SOURCE_FOR_REPLACE}' replaced with '{Config.TEXT_NEW_VALUE}' - successfully.") |
| 86 | + else: |
| 87 | + print("Failed to replace text in document.") |
| 88 | + |
| 89 | + def replace_page_texts(self): |
| 90 | + """ Replace text on the page in PDF document """ |
| 91 | + if not self.pdf_api: |
| 92 | + return |
| 93 | + |
| 94 | + text_replace_obj = TextReplace(old_value=Config.TEXT_NEW_VALUE, new_value=Config.TEXT_SOURCE_FOR_REPLACE, regex=False) |
| 95 | + |
| 96 | + text_replace_request = TextReplaceListRequest([text_replace_obj]) |
| 97 | + |
| 98 | + response = self.pdf_api.post_page_text_replace( |
| 99 | + Config.PDF_DOCUMENT_NAME, |
| 100 | + Config.PAGE_NUMBER, |
| 101 | + text_replace_request |
| 102 | + ) |
| 103 | + |
| 104 | + if response.code == 200: |
| 105 | + print(f"Text '{Config.TEXT_NEW_VALUE}' replaced with '{Config.TEXT_SOURCE_FOR_REPLACE}' - successfully.") |
| 106 | + else: |
| 107 | + print("Failed to replace text in document.") |
| 108 | + |
| 109 | + |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + pdf_texts = PdfTexts() |
| 113 | + pdf_texts.upload_document() |
| 114 | + pdf_texts.replace_document_texts() |
| 115 | + pdf_texts.replace_page_texts() |
| 116 | + pdf_texts.download_result() |
0 commit comments