Skip to content

Commit b6e3530

Browse files
authored
Merge pull request #32 from aspose-pdf-cloud/holub
Fix: PDF pages (update metadata code snippet)
2 parents 4578535 + 4731be5 commit b6e3530

File tree

2 files changed

+199
-12
lines changed

2 files changed

+199
-12
lines changed

pdf/nodejs/metadata/remove/_index.md

Lines changed: 74 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,11 @@ Aspose.PDF Cloud developers can easily load & remove metadata from PDF in just a
4343

4444
{{% /blocks/products/pf/agp/text %}}
4545

46-
1. Load your Application Secret and Key from the JSON file or set credentials in another way
47-
1. Create an object to connect to the Cloud API
46+
1. Create an object to connect to the Pdf.Cloud API
4847
1. Upload your document file
49-
1. Perform the deleting the metadata using ///////
48+
1. Create a new XmpMetadataProperty. Set the name of the property you want to delete as the Key and `null` as the value
49+
1. Delete Metadata in the document using postXmpMetadata() function
50+
1. Perform some action after successful addition
5051
1. Download the result if needed it
5152

5253
{{% /blocks/products/pf/agp/feature-section-col %}}
@@ -71,7 +72,76 @@ It is easy to get started with Aspose.PDF Cloud Node.js SDK and there is nothing
7172

7273
```js
7374

74-
75+
import credentials from "./credentials.json" with { type: "json" };
76+
import fs from 'node:fs/promises';
77+
import path from 'node:path';
78+
import { PdfApi } from "asposepdfcloud";
79+
import { XmpMetadata } from "asposepdfcloud/src/models/xmpMetadata.js";
80+
import { XmpMetadataProperty } from "asposepdfcloud/src/models/xmpMetadataProperty.js";
81+
82+
const configParams = {
83+
LOCAL_FOLDER: "C:\\Samples\\",
84+
PDF_DOCUMENT_NAME: "sample.pdf",
85+
LOCAL_RESULT_DOCUMENT_NAME: "output_sample.pdf",
86+
};
87+
88+
const pdfApi = new PdfApi(credentials.id, credentials.key);
89+
90+
const pdfMetadatas = {
91+
async uploadDocument() {
92+
const pdfFilePath = path.join(configParams.LOCAL_FOLDER, configParams.PDF_DOCUMENT_NAME);
93+
const pdfFileData = await fs.readFile(pdfFilePath);
94+
await pdfApi.uploadFile(configParams.PDF_DOCUMENT_NAME, pdfFileData);
95+
},
96+
97+
async downloadResult() {
98+
const changedPdfData = await pdfApi.downloadFile(configParams.PDF_DOCUMENT_NAME);
99+
const filePath = path.join(configParams.LOCAL_FOLDER, configParams.LOCAL_RESULT_DOCUMENT_NAME);
100+
await fs.writeFile(filePath, changedPdfData.body);
101+
console.log("Downloaded: " + filePath);
102+
},
103+
104+
async getMetadata () {
105+
const responseMetadata = await pdfApi.getXmpMetadataJson(configParams.PDF_DOCUMENT_NAME);
106+
107+
if (responseMetadata.response.status == 200)
108+
{
109+
const props = responseMetadata.body.properties;
110+
props.forEach((prop) =>{
111+
console.log(prop.key);
112+
});
113+
}
114+
},
115+
116+
async deleteMetadata () {
117+
const prop = new XmpMetadataProperty();
118+
prop.key = 'dc:creator';
119+
prop.value = null; // null value means delete property...
120+
prop.namespaceUri = 'http://purl.org/dc/elements/1.1/';
121+
122+
const metadata = new XmpMetadata();
123+
metadata.properties = [prop];
124+
125+
const response = await pdfApi.postXmpMetadata(configParams.PDF_DOCUMENT_NAME, metadata);
126+
127+
if (response.body.code == 200) {
128+
console.log("Delete metadata '" + prop.key + "' successful!");
129+
return true;
130+
}
131+
},
132+
}
133+
134+
async function main() {
135+
try {
136+
await pdfMetadatas.uploadDocument();
137+
await pdfMetadatas.getMetadata();
138+
await pdfMetadatas.deleteMetadata();
139+
await pdfMetadatas.getMetadata();
140+
await pdfMetadatas.downloadResult();
141+
} catch (error) {
142+
console.error("Error:", error.message);
143+
}
144+
}
75145
```
76146

77147
{{% /blocks/products/pf/agp/code-block %}}

pdf/python/text/replace/_index.md

Lines changed: 125 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,13 +50,15 @@ Aspose.PDF Cloud developers can easily load & replace Text in PDF in just a few
5050

5151
{{% /blocks/products/pf/agp/text %}}
5252

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
6062

6163
{{% /blocks/products/pf/agp/feature-section-col %}}
6264

@@ -76,7 +78,122 @@ It is easy to get started with Aspose.PDF Cloud Python SDK and there is nothing
7678

7779
```python
7880

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()
80197
```
81198

82199
{{% /blocks/products/pf/agp/code-block %}}

0 commit comments

Comments
 (0)