Replace Text - Text Replacement API
PDF4me Replace Text enables you to find and replace text in Word documents with advanced search options. This API service processes Word files and performs multiple replacement operations with case-sensitive matching and whole word matching. The API receives Word document content through REST API calls, utilizing Base64 encoding for secure transmission. With support for multiple find and replace operations in a single request, this solution is ideal for document automation, template processing, and content management workflows.
Authenticating Your API Request
To access the PDF4me REST API, every request must include proper authentication credentials. Authentication ensures secure communication and validates your identity as an authorized user of the REST API.
Key Features
- Multiple Text Replacements: Perform multiple find and replace operations in a single action
- Advanced Search Options: Case-sensitive matching and whole word matching
- Sequential Processing: Multiple replacements processed in specified order
- Flexible Matching: Exact matches, partial matches, or whole word matches
- Simple Structure: Easy-to-use array of find and replace operations
REST API Endpoint
The PDF4me REST API uses standard HTTP methods to interact with resources. All text replacement operations are performed through a single endpoint:
- Method: POST
- Endpoint:
office/ApiV2Word/ReplaceText
REST API Parameters
Complete list of parameters for the Replace Text REST API. Parameters are organized by category for better understanding and implementation.
Important: Parameters marked with an asterisk (*) are required. The phrases array must contain at least one replacement phrase.
Required Parameters
| Parameter | Type | Description | Example |
|---|---|---|---|
| document* | Object | Document reference. Must contain Name (string) — Word file name with .docx extension | { "Name": "document.docx" } |
| docContent* | Base64 | Word document content encoded in Base64. Text replacement is performed on this document | UEsDBBQABgAIAAAA... |
| phrases* | Array | Array of replacement objects. Must contain at least one replacement. Each replacement is processed sequentially in the order specified | See example below |
Text Replacement Object Structure (phrases array)
Each item in the phrases array must be an object with the following structure:
| Parameter | Type | Description | Example |
|---|---|---|---|
| findText* | String | Text string to search for in the document. Cannot be null or empty. Case-sensitive or case-insensitive based on matchCase setting. All instances of this text will be replaced | "old text" |
| replaceText | String | Text to replace the found text with. Can be empty string to remove found text. Default: empty string (removes found text) | "new text" |
| matchCase | Boolean | Case-sensitive matching. true = Search is case-sensitive (exact case match required), false = Search is case-insensitive (default). Controls whether "The" matches "the" or only "The" | false |
| matchWholeWord | Boolean | Whole word matching. true = Match only complete words (not partial matches), false = Match partial text within words (default). Prevents "the" from matching "there" or "other" | false |
Optional Parameters
| Parameter | Type | Description | Example |
|---|---|---|---|
| cultureName | String | Culture code for document processing (e.g., "en-US", "de-DE", "fr-FR") | en-US |
Text Replacement Processing
- Each replacement is processed sequentially in the order specified
- Multiple replacements can be performed on the same document
- All instances of Find Text are replaced (unless using whole word matching)
Output
The PDF4me Replace Text REST API returns different responses based on the processing mode. The API returns the Word document as a Base64-encoded string in JSON format, not as binary data.
- Success Response
- Asynchronous Processing
- Error Responses
- Response Format Details
Synchronous Processing (Default)
The API processes the request and returns:
Status Code: 200 OK
Content-Type: application/json
Response Body:
{
"document": "UEsDBBQABgAIAAAAIQDfpNJsWgEAACAFAAATAAgCW0NvbnRlbnRfVHlwZXNdLnhtbCCiBAIooAAC...",
"fileName": "document.docx",
"success": true,
"errorMessage": null
}
Response Fields:
- document (string): The Word document with text replacements applied, encoded as Base64 string
- fileName (string): The output Word file name
- success (boolean): Indicates whether the request succeeded
- errorMessage (string or null): Error details when success is false
How to Use:
- Extract the
documentfield from the JSON response (Base64) - Decode the Base64 string to get the binary Word document data
- Save or process the Word file as needed
Example (JavaScript):
const response = await fetch(url, options);
const data = await response.json();
const wordBytes = atob(data.document); // Decode Base64
// Save or process wordBytes
Asynchronous Processing
Asynchronous behavior (202 Accepted with polling) is controlled by server configuration, not by a request body parameter. When enabled, the API may return a 202 status with a polling URL in the Location header. Poll the URL with GET requests until you receive 200 OK with the same response shape (document, fileName, success, errorMessage).
Error Responses
The API returns standard HTTP error codes with error details:
- Invalid request parameters
- Missing required fields (
documentwithName,docContent,phrases) - Phrases array is null or empty
- Find Text is null or empty in a replacement
- Invalid Base64 encoding in
docContent - Invalid or corrupted Word document
- Invalid font size or formatting parameters
- Invalid or missing API key
- API key not properly Base64 encoded in Authorization header
- Missing
Authorization: Basicheader
- Server-side processing error
- Word document processing failure
- Text replacement failure
Error Response Format:
{
"error": "Error message describing what went wrong"
}
Response Format Details
Important: The API always returns JSON, never binary Word data directly.
Response Structure:
{
"document": "string", // Base64-encoded Word document content
"fileName": "string", // Output Word filename
"success": true,
"errorMessage": "string or null"
}
Content-Type Header:
- Success:
application/json - The Word document is embedded as a Base64 string within the JSON response
Why Base64?
- JSON-safe encoding for binary data
- Easy to transmit over HTTP
- Compatible with all programming languages
- Can be directly embedded in JSON without escaping issues
Decoding Base64 to Word Document:
JavaScript/Node.js:
const base64 = response.docContent;
const binary = atob(base64); // Browser
// OR
const binary = Buffer.from(base64, 'base64'); // Node.js
Python:
import base64
word_bytes = base64.b64decode(response['docContent'])
with open('output.docx', 'wb') as f:
f.write(word_bytes)
C#:
byte[] wordBytes = Convert.FromBase64String(response.docContent);
File.WriteAllBytes("output.docx", wordBytes);
Request Example
Header
Content-Type: application/json
Authorization: Basic YOUR_BASE64_ENCODED_API_KEY
Note:
- Get your API key from the PDF4me Dashboard
- The API key must be Base64 encoded and prefixed with "Basic " in the Authorization header
- Example: If your API key is
abc123, encode it to Base64 and useAuthorization: Basic YWJjMTIz
Payload
Basic Example (Single Replacement):
{
"document": { "Name": "document.docx" },
"docContent": "base64EncodedDocumentContent",
"phrases": [
{
"findText": "old text",
"replaceText": "new text",
"matchCase": false,
"matchWholeWord": false
}
],
"cultureName": "en-US"
}
Advanced Example (Multiple Replacements):
{
"document": { "Name": "document.docx" },
"docContent": "base64EncodedDocumentContent",
"phrases": [
{
"findText": "[COMPANY_NAME]",
"replaceText": "Acme Corporation",
"matchCase": false,
"matchWholeWord": false
},
{
"findText": "[DATE]",
"replaceText": "2024-01-15",
"matchCase": false,
"matchWholeWord": false
},
{
"findText": "[CONTACT_EMAIL]",
"replaceText": "[email protected]",
"matchCase": false,
"matchWholeWord": false
}
],
"cultureName": "en-US"
}
Code Samples
The PDF4me Replace Text REST API provides code samples in multiple programming languages. Choose the language that best fits your development environment:
- C#
- Java
- JavaScript
- Python
- Salesforce
- n8n
- Google Script
- AWS Lambda
Google Script Sample
Google Apps Script implementation for Google Workspace integration:
Industry Use Cases & Applications
- Legal & Professional Services
- Business & Enterprise
- Education & Research
- Finance & Banking
Legal & Professional Services Use Cases
- Contract Processing: Replace placeholder text with client-specific information
- Legal Document Automation: Update case numbers, client names, and dates
- Template Standardization: Standardize legal terminology and formatting
- Client Communication: Personalize legal documents for specific clients
Business & Enterprise Use Cases
- Proposal Generation: Replace proposal templates with client-specific information
- Marketing Material Creation: Update marketing templates with campaign details
- Client Communication: Personalize sales documents for specific prospects
- Report Standardization: Standardize sales terminology and formatting
Education & Research Use Cases
- Medical Report Generation: Replace medical templates with patient-specific information
- Patient Communication: Personalize medical documents for specific patients
- Research Documentation: Update research templates with study-specific data
- Compliance Documentation: Update medical compliance templates with current standards
Finance & Banking Use Cases
- Financial Report Generation: Replace template data with actual financial metrics
- Invoice Processing: Update invoice templates with client and payment information
- Budget Document Automation: Replace budget placeholders with actual figures
- Audit Report Generation: Update audit templates with specific audit findings