Replace Text with Image - Image Replacement API
PDF4me Replace Text with Image enables you to replace specified text with images in Word documents with advanced page filtering and size control options. This API service processes Word files and replaces text placeholders with images using precise text matching, customizable sizing with aspect ratio preservation, page-specific targeting, and flexible filtering options. The API receives Word document content and image data through REST API calls, utilizing Base64 encoding for secure transmission. With support for multiple image formats and full control over replacement behavior, this solution is ideal for document automation, template processing, and dynamic content insertion 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
- Text-to-Image Replacement: Replace specific text strings with images throughout documents
- Precise Text Matching: Case-sensitive text search and replacement
- Image Size Control: Customize image dimensions with width and height parameters
- Aspect Ratio Preservation: Maintain image proportions during resizing
- Page Filtering: Target specific pages or page ranges for replacement
- Advanced Filtering: Skip first page, target odd/even pages, or specify exact page numbers
- Multiple Image Formats: Support for PNG, JPG, JPEG, BMP, GIF formats
- Flexible Positioning: Insert images as Word shapes with precise positioning
REST API Endpoint
The PDF4me REST API uses standard HTTP methods to interact with resources. All text-to-image replacement operations are performed through a single endpoint:
- Method: POST
- Endpoint:
office/ApiV2Word/ReplaceTextWithImage
REST API Parameters
Complete list of parameters for the Replace Text with Image REST API. Parameters are organized by category for better understanding and implementation.
Important: Parameters marked with an asterisk (*) are required. Advanced parameters provide fine-grained control over image sizing and page filtering.
Required Parameters
| Parameter | Type | Description | Example |
|---|---|---|---|
| document* | Object | Document descriptor. Must include Name (string): output Word file name with .docx extension | { "Name": "document.docx" } |
| docContent* | Base64 | Word document content encoded in Base64. Text replacement is performed on this document. Must be valid Word document (.docx, .doc formats) | base64EncodedDocumentContent |
| findText* | String | Text string to search for in the document. Case-sensitive. All instances will be replaced with the image. Cannot be null or empty. Examples: "[LOGO]", "SIGN_HERE" | "text to replace" |
| imageContent* | Base64 | Replacement image file content encoded in Base64. Must be valid image (PNG, JPG, JPEG, BMP, GIF) | base64EncodedImageContent |
Optional Parameters
| Parameter | Type | Description | Example |
|---|---|---|---|
| width | Number (double) | Image width | 200 |
| height | Number (double) | Image height | 100 |
| maintainAspectRatio | Boolean | Maintain image proportions during resizing. Default: true | true |
| skipFirstPage | Boolean | Skip replacement on first page. true = skip first page, false = include (default). Useful for cover/title pages | false |
| applyTo | String | Target scope for replacement | — |
| pageNumbers | String | Specific page numbers or ranges (e.g., "1,2,3" or "1,3,5-7"). Empty = all pages | "1,2,3" |
| ignorePageNumbers | String | Page numbers to exclude from replacement | — |
| cultureName | String | Culture code (e.g., "en-US", "fr-FR", "de-DE"). Default: null | en-US |
Page Filtering
The API supports page filtering through the following parameters:
- skipFirstPage: Controls whether to skip the first page
- pageNumbers: Specifies which pages to process (empty string = all pages)
- ignorePageNumbers: Page numbers to exclude
Supported Image Formats
The Replace Text with Image API supports various image formats for maximum compatibility:
| Format | Extension | Description |
|---|---|---|
| PNG | .png | Portable Network Graphics - best for logos and graphics with transparency |
| JPEG | .jpg, .jpeg | Joint Photographic Experts Group - best for photographs and complex images |
| BMP | .bmp | Bitmap - uncompressed format, larger file sizes |
| GIF | .gif | Graphics Interchange Format - supports animation and transparency |
Output
The PDF4me Replace Text with Image REST API returns a JSON response (ApiV2WordApiCallRes). On success the API returns the Word document as a Base64-encoded string in the document field, not as binary data.
- Success Response
- Error Responses
- Response Format Details
Success Response
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 replaced by images, encoded as Base64
- fileName (string): The output Word file name
- success (boolean): Whether the operation succeeded
- errorMessage (string): Error message if success is false; otherwise null
How to Use:
- Check
success; if true, extract thedocumentfield from the JSON response - Decode the Base64 string to get the binary Word document data
- Save or process the Word file using
fileName
Example (JavaScript):
const response = await fetch(url, options);
const data = await response.json();
if (!data.success) throw new Error(data.errorMessage);
const wordBytes = atob(data.document);
// Save or process wordBytes
Error Responses
The API returns standard HTTP error codes with error details:
- Invalid request parameters
- Missing required fields (
document,docContent,findText,imageContent) - FindText is null or empty
- ImageContent is null or empty
- Invalid Base64 encoding in
docContentorimageContent - Invalid or corrupted Word document
- Invalid or corrupted image file
- No pages match the filtering criteria
- 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
- Image insertion 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 (ApiV2WordApiCallRes):
{
"document": "string", // Base64-encoded Word document content
"fileName": "string", // Output Word filename
"success": true,
"errorMessage": 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.document;
const binary = atob(base64); // Browser
// OR
const binary = Buffer.from(base64, 'base64'); // Node.js
Python:
import base64
word_bytes = base64.b64decode(response['document'])
with open('output.docx', 'wb') as f:
f.write(word_bytes)
C#:
byte[] wordBytes = Convert.FromBase64String(response.document);
File.WriteAllBytes(response.fileName, 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 (Required Fields Only):
{
"document": { "Name": "document.docx" },
"docContent": "base64EncodedDocumentContent",
"findText": "text to replace",
"imageContent": "base64EncodedImageContent",
"cultureName": "en-US"
}
Advanced Example (With Optional Fields):
{
"document": { "Name": "document.docx" },
"docContent": "base64EncodedDocumentContent",
"findText": "text to replace",
"imageContent": "base64EncodedImageContent",
"width": 200,
"height": 100,
"maintainAspectRatio": true,
"skipFirstPage": true,
"pageNumbers": "1,2,3",
"ignorePageNumbers": null,
"cultureName": "en-US"
}
Code Samples
The PDF4me Replace Text with Image 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
C# (CSharp) Sample
Complete C# implementation for replacing text with images in Word documents:
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 signature placeholders with authorized signatures
- Legal Document Automation: Insert firm logos and watermarks into legal documents
- Client Document Personalization: Add client-specific images to legal documents
- Compliance Documentation: Insert compliance stamps and seals into documents
Business & Enterprise Use Cases
- Proposal Generation: Insert company logos and product images into proposals
- Marketing Material Creation: Replace placeholder text with marketing images
- Client Presentation Automation: Insert client-specific images into presentations
- Sales Report Generation: Insert sales charts and graphs into reports
Education & Research Use Cases
- Medical Report Generation: Insert medical charts and diagrams into reports
- Patient Document Processing: Insert medical facility logos into patient documents
- Research Documentation: Insert research charts and graphs into research papers
- Compliance Documentation: Insert medical compliance stamps into documents
Finance & Banking Use Cases
- Financial Report Generation: Insert charts and graphs into financial reports
- Invoice Processing: Replace logo placeholders with company logos
- Audit Documentation: Insert audit stamps and signatures into audit reports
- Budget Report Automation: Insert budget charts into budget documents