|
| 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 | + IMAGE_STAMP_FILE ="sample.png" |
| 17 | + PAGE_NUMBER = 2 |
| 18 | + STAMP_TEXT = "NEW TEXT STAMP" |
| 19 | + IMAGE_STAMP_LLY = 800 |
| 20 | + IMAGE_STAMP_WIDTH = 24 |
| 21 | + IMAGE_STAMP_HEIGHT = 24 |
| 22 | + |
| 23 | +class PdfStamps: |
| 24 | + """ Class for managing PDF stamps using Aspose PDF Cloud API. """ |
| 25 | + def __init__(self, credentials_file: Path = Config.CREDENTIALS_FILE): |
| 26 | + self.pdf_api = None |
| 27 | + self._init_api(credentials_file) |
| 28 | + |
| 29 | + def _init_api(self, credentials_file: Path): |
| 30 | + """ Initialize the API client. """ |
| 31 | + try: |
| 32 | + with credentials_file.open("r", encoding="utf-8") as file: |
| 33 | + credentials = json.load(file) |
| 34 | + api_key, app_id = credentials.get("key"), credentials.get("id") |
| 35 | + if not api_key or not app_id: |
| 36 | + raise ValueError("init_api(): Error: Missing API keys in the credentials file.") |
| 37 | + self.pdf_api = PdfApi(ApiClient(api_key, app_id)) |
| 38 | + except (FileNotFoundError, json.JSONDecodeError, ValueError) as e: |
| 39 | + logging.error(f"init_api(): Failed to load credentials: {e}") |
| 40 | + |
| 41 | + def _ensure_api_initialized(self): |
| 42 | + """ Check if the API is initialized before making API calls. """ |
| 43 | + if not self.pdf_api: |
| 44 | + logging.error("ensure_api_initialized(): PDF API is not initialized. Operation aborted.") |
| 45 | + return False |
| 46 | + return True |
| 47 | + |
| 48 | + def upload_file(self, fileName: str): |
| 49 | + """ Upload a local fileName to the Aspose Cloud server. """ |
| 50 | + if not self._ensure_api_initialized(): |
| 51 | + return |
| 52 | + |
| 53 | + file_path = Config.LOCAL_FOLDER / fileName |
| 54 | + try: |
| 55 | + self.pdf_api.upload_file(fileName, str(file_path)) |
| 56 | + logging.info(f"upload_file(): File '{fileName}' uploaded successfully.") |
| 57 | + except Exception as e: |
| 58 | + logging.error(f"upload_document(): Failed to upload file: {e}") |
| 59 | + |
| 60 | + def upload_document(self): |
| 61 | + """ Upload a PDF document to the Aspose Cloud server. """ |
| 62 | + self.upload_file(Config.PDF_DOCUMENT_NAME) |
| 63 | + |
| 64 | + def download_result(self): |
| 65 | + """ Download the processed PDF document from the Aspose Cloud server. """ |
| 66 | + if not self._ensure_api_initialized(): |
| 67 | + return |
| 68 | + |
| 69 | + try: |
| 70 | + temp_file = self.pdf_api.download_file(Config.PDF_DOCUMENT_NAME) |
| 71 | + local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME |
| 72 | + shutil.move(temp_file, str(local_path)) |
| 73 | + logging.info(f"download_result(): File successfully downloaded: {local_path}") |
| 74 | + except Exception as e: |
| 75 | + logging.error(f"download_result(): Failed to download file: {e}") |
| 76 | + |
| 77 | + def add_document_stamps(self): |
| 78 | + """ Adds a text stamp to a specific page in a PDF document. """ |
| 79 | + |
| 80 | + text_stamp: Stamp = Stamp( |
| 81 | + type = StampType.TEXT, |
| 82 | + background = True, |
| 83 | + horizontal_alignment = HorizontalAlignment.CENTER, |
| 84 | + text_alignment = HorizontalAlignment.CENTER, |
| 85 | + value=Config.STAMP_TEXT |
| 86 | + ) |
| 87 | + |
| 88 | + image_stamp: Stamp = Stamp( |
| 89 | + type = StampType.IMAGE, |
| 90 | + background = True, |
| 91 | + horizontal_alignment = HorizontalAlignment.CENTER, |
| 92 | + text_alignment = HorizontalAlignment.CENTER, |
| 93 | + value = "NEW IMAGE STAMP", |
| 94 | + file_name = Config.IMAGE_STAMP_FILE, |
| 95 | + y_indent = Config.IMAGE_STAMP_LLY, |
| 96 | + width = Config.IMAGE_STAMP_WIDTH, |
| 97 | + height = Config.IMAGE_STAMP_HEIGHT |
| 98 | + ) |
| 99 | + |
| 100 | + responseTextStamp: AsposeResponse = self.pdf_api.post_document_text_stamps(Config.PDF_DOCUMENT_NAME, [ text_stamp ]) |
| 101 | + responseImageStamp: AsposeResponse = self.pdf_api.post_document_image_stamps(Config.PDF_DOCUMENT_NAME, [ image_stamp ]) |
| 102 | + |
| 103 | + if responseTextStamp.code == 200 and responseImageStamp.code == 200: |
| 104 | + logging.info(f"Text stamp '{Config.STAMP_TEXT}' and image stamp '{Config.IMAGE_STAMP_FILE}' added to the document '{Config.PDF_DOCUMENT_NAME}'.") |
| 105 | + else: |
| 106 | + if responseTextStamp.code != 200: |
| 107 | + logging.error(f"Failed to add text stamp '{Config.STAMP_TEXT}' to the document '{Config.PDF_DOCUMENT_NAME}'.") |
| 108 | + else: |
| 109 | + logging.error(f"Failed to add image stamp '{Config.IMAGE_STAMP_FILE}' to the document '{Config.PDF_DOCUMENT_NAME}'.") |
| 110 | + |
| 111 | +if __name__ == "__main__": |
| 112 | + pdf_stamps = PdfStamps() |
| 113 | + pdf_stamps.upload_document() |
| 114 | + pdf_stamps.upload_file(Config.IMAGE_STAMP_FILE) |
| 115 | + pdf_stamps.add_document_stamps() |
| 116 | + pdf_stamps.download_result() |
0 commit comments