@@ -50,13 +50,15 @@ Aspose.PDF Cloud developers can easily load & replace Text in PDF in just a few
50
50
51
51
{{% /blocks/products/pf/agp/text %}}
52
52
53
- 1 . Install [ Python SDK] ( https://pypi.org/project/asposepdfcloud/ ) .
54
- 1 . Go to the [ Aspose Cloud Dashboard] ( https://dashboard.aspose.cloud/ ) .
55
- 1 . Create a new [ Account] ( https://docs.aspose.cloud/display/storagecloud/Creating+and+Managing+Account ) to access all applications and services or Sign In to your account.
56
- 1 . Click on Applications in the left menu to get Client Id and Client Secret.
57
- 1 . Check out the [ Developer Guide] ( https://docs.aspose.cloud/pdf/developer-guide/ ) to replace Text in PDF via Python.
58
- 1 . Check out our [ GitHub repository] ( https://github.com/aspose-pdf-cloud/aspose-pdf-cloud-python/ ) for a complete API list along with working examples.
59
- 1 . Check out the [ API Reference page] ( https://reference.aspose.cloud/pdf/#/Document ) for the description of APIs parameters.
53
+ 1 . Defining Configuration Parameters
54
+ 1 . Setting Up Logging
55
+ 1 . Creating the PdfTexts Class
56
+ 1 . Initializing the API Client
57
+ 1 . Ensuring API Initialization
58
+ 1 . Uploading the PDF Document
59
+ 1 . Replacing Text in the PDF Document
60
+ 1 . Specific Page Replacement
61
+ 1 . Downloading the Processed PDF Document
60
62
61
63
{{% /blocks/products/pf/agp/feature-section-col %}}
62
64
@@ -76,7 +78,122 @@ It is easy to get started with Aspose.PDF Cloud Python SDK and there is nothing
76
78
77
79
``` python
78
80
79
-
81
+ import shutil
82
+ import json
83
+ import logging
84
+ from pathlib import Path
85
+ from asposepdfcloud import ApiClient, PdfApi, TextReplace, TextReplaceListRequest
86
+
87
+ class Config :
88
+ """ Configuration parameters."""
89
+ CREDENTIALS_FILE = Path(r " C:\\ Projects\\ ASPOSE\\ Pdf. Cloud\\ Credentials\\ credentials. json" )
90
+ LOCAL_FOLDER = Path(r " C:\\ Samples" )
91
+ PDF_DOCUMENT_NAME = " sample.pdf"
92
+ LOCAL_RESULT_DOCUMENT_NAME = " output_sample.pdf"
93
+ PAGE_NUMBER = 2
94
+ TEXT_SOURCE_FOR_REPLACE = " YOUR source text"
95
+ TEXT_NEW_VALUE = " YOUR new text"
96
+
97
+ # Configure logging
98
+ logging.basicConfig(level = logging.INFO , format = " %(asctime)s - %(levelname)s - %(message)s " )
99
+
100
+ class PdfTexts :
101
+ """ Class for managing PDF texts using Aspose PDF Cloud API."""
102
+
103
+ def __init__ (self , credentials_file : Path = Config.CREDENTIALS_FILE ):
104
+ self .pdf_api = None
105
+ self ._init_api(credentials_file)
106
+
107
+ def _init_api (self , credentials_file : Path):
108
+ """ Initialize the API client."""
109
+ try :
110
+ with credentials_file.open(" r" , encoding = " utf-8" ) as file :
111
+ credentials = json.load(file )
112
+ api_key, app_id = credentials.get(" key" ), credentials.get(" id" )
113
+ if not api_key or not app_id:
114
+ raise ValueError (" Error: Missing API keys in the credentials file." )
115
+ self .pdf_api = PdfApi(ApiClient(api_key, app_id))
116
+ except (FileNotFoundError , json.JSONDecodeError, ValueError ) as e:
117
+ logging.error(f " Failed to load credentials: { e} " )
118
+
119
+ def _ensure_api_initialized (self ):
120
+ """ Check if the API is initialized before making API calls."""
121
+ if not self .pdf_api:
122
+ logging.error(" PDF API is not initialized. Operation aborted." )
123
+ return False
124
+ return True
125
+
126
+ def upload_document (self ):
127
+ """ Upload a PDF document to the Aspose Cloud server."""
128
+ if not self ._ensure_api_initialized():
129
+ return
130
+
131
+ file_path = Config.LOCAL_FOLDER / Config.PDF_DOCUMENT_NAME
132
+ try :
133
+ self .pdf_api.upload_file(Config.PDF_DOCUMENT_NAME , str (file_path))
134
+ logging.info(f " File { Config.PDF_DOCUMENT_NAME } uploaded successfully. " )
135
+ except Exception as e:
136
+ logging.error(f " Failed to upload file: { e} " )
137
+
138
+ def download_result (self ):
139
+ """ Download the processed PDF document from the Aspose Cloud server """
140
+ if not self ._ensure_api_initialized():
141
+ return
142
+
143
+ try :
144
+ temp_file = self .pdf_api.download_file(Config.PDF_DOCUMENT_NAME )
145
+ local_path = Config.LOCAL_FOLDER / Config.LOCAL_RESULT_DOCUMENT_NAME
146
+ shutil.move(temp_file, str (local_path))
147
+ logging.info(f " download_result(): File successfully downloaded: { local_path} " )
148
+ except Exception as e:
149
+ logging.error(f " download_result(): Failed to download file: { e} " )
150
+
151
+ def replace_document_texts (self ):
152
+ """ Replace text in the PDF document """
153
+ if not self .pdf_api:
154
+ return
155
+
156
+ text_replace_obj = TextReplace(old_value = Config.TEXT_SOURCE_FOR_REPLACE , new_value = Config.TEXT_NEW_VALUE , regex = False )
157
+
158
+ text_replace_request = TextReplaceListRequest([text_replace_obj])
159
+
160
+ response = self .pdf_api.post_document_text_replace(
161
+ Config.PDF_DOCUMENT_NAME , text_replace_request
162
+ )
163
+
164
+ if response.code == 200 :
165
+ print (f " Text ' { Config.TEXT_SOURCE_FOR_REPLACE } ' replaced with ' { Config.TEXT_NEW_VALUE } ' - successfully. " )
166
+ else :
167
+ print (" Failed to replace text in document." )
168
+
169
+ def replace_page_texts (self ):
170
+ """ Replace text on the page in PDF document """
171
+ if not self .pdf_api:
172
+ return
173
+
174
+ text_replace_obj = TextReplace(old_value = Config.TEXT_NEW_VALUE , new_value = Config.TEXT_SOURCE_FOR_REPLACE , regex = False )
175
+
176
+ text_replace_request = TextReplaceListRequest([text_replace_obj])
177
+
178
+ response = self .pdf_api.post_page_text_replace(
179
+ Config.PDF_DOCUMENT_NAME ,
180
+ Config.PAGE_NUMBER ,
181
+ text_replace_request
182
+ )
183
+
184
+ if response.code == 200 :
185
+ print (f " Text ' { Config.TEXT_NEW_VALUE } ' replaced with ' { Config.TEXT_SOURCE_FOR_REPLACE } ' - successfully. " )
186
+ else :
187
+ print (" Failed to replace text in document." )
188
+
189
+
190
+
191
+ if __name__ == " __main__" :
192
+ pdf_texts = PdfTexts()
193
+ pdf_texts.upload_document()
194
+ pdf_texts.replace_document_texts()
195
+ pdf_texts.replace_page_texts()
196
+ pdf_texts.download_result()
80
197
```
81
198
82
199
{{% /blocks/products/pf/agp/code-block %}}
0 commit comments