When using regular expressions in JSON payloads, ensure that backslashes are properly escaped. For example, a single backslash \ should be written as \\.
HTTP auth user name if required to access source URL.
httppassword
string
No
-
HTTP auth password if required to access source URL.
searchStrings
array[string]
Yes
-
The array of strings to search.
replacementLimit
integer
No
0
Limit the number of searches & replacements for every item. The value 0 means every found occurrence will be replaced.
caseSensitive
boolean
No
true
Set to false to don’t use case-sensitive search.
regex
boolean
No
false
Set to true to use regular expression for search string(s).
name
string
No
-
File name for the generated output, the input must be in string format.
expiration
integer
No
60
Set the expiration time for the output link in minutes. After this specified duration, any generated output file(s) will be automatically deleted from PDF.co Temporary Files Storage. The maximum duration for link expiration varies based on your current subscription plan. To store permanent input files (e.g. re-usable images, pdf templates, documents) consider using PDF.co Built-In Files Storage.
pages
string
No
all pages
Specify page indices as comma-separated values or ranges to process (e.g. “0, 1, 2-” or “1, 2, 3-7”). The first-page index is 0. Use ”!” before a number for inverted page numbers (e.g. “!0” for the last page). If not specified, the default configuration processes all pages. The input must be in string format.
If you require to crop empty space around an inserted image use the following: profiles": { 'AutoCropImages': true }
outputDataFormat
string
No
-
If you require your output as base64 format, set this to base64
DataEncryptionAlgorithm
string
No
-
Controls the encryption algorithm used for data encryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256.
DataEncryptionKey
string
No
-
Controls the encryption key used for data encryption. See User-Controlled Encryption for more information.
DataEncryptionIV
string
No
-
Controls the encryption IV used for data encryption. See User-Controlled Encryption for more information.
DataDecryptionAlgorithm
string
No
-
Controls the decryption algorithm used for data decryption. See User-Controlled Encryption for more information. The available algorithms are: AES128, AES192, AES256.
DataDecryptionKey
string
No
-
Controls the decryption key used for data decryption. See User-Controlled Encryption for more information.
DataDecryptionIV
string
No
-
Controls the decryption IV used for data decryption. See User-Controlled Encryption for more information.
YAdjustmentForReplacementText
integer
No
-
Adjust the vertical position of the replaced text, ensuring proper alignment with the rest of the document. See Adjust Text Alignment for more details.
Users may have encountered an issue when using this API endpoint to replace text in a PDF document. The replaced text might appear slightly higher than the original text or the surrounding text, causing alignment issues.
To fix this issue, we have added a new parameter called YAdjustmentForReplacementText in the profiles parameter of the API request. This parameter allows you to adjust the vertical position of the replaced text, ensuring proper alignment with the rest of the document. Negative values for this parameter move text up, positive values move text down.
Here’s an example of how to use the YAdjustmentForReplacementText parameter. In this example API request, the YAdjustmentForReplacementText parameter has been set to -1, which moves the replaced text 1 unit up vertically, resulting in better alignment with the original text.
var https = require("https");var path = require("path");var fs = require("fs");// The authentication key (API Key).// Get your own by registering at https://app.pdf.coconst API_KEY = "***********************************";// Direct URL of source PDF file.// You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/ const SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-to-text/sample.pdf";// PDF document password. Leave empty for unprotected documents.const Password = "";// Destination PDF file nameconst DestinationFile = "./result.pdf";// Prepare request to `Replace Text from PDF` API endpointvar queryPath = `/v1/pdf/edit/replace-text`;// JSON payload for api requestvar jsonPayload = JSON.stringify({ name: path.basename(DestinationFile), password: Password, url: SourceFileUrl, searchString: 'Your Company Name', replaceString: 'XYZ LLC'});var reqOptions = { host: "api.pdf.co", method: "POST", path: queryPath, headers: { "x-api-key": API_KEY, "Content-Type": "application/json", "Content-Length": Buffer.byteLength(jsonPayload, 'utf8') }};// Send requestvar postRequest = https.request(reqOptions, (response) => { response.on("data", (d) => { // Parse JSON response var data = JSON.parse(d); if (data.error == false) { // Download PDF file var file = fs.createWriteStream(DestinationFile); https.get(data.url, (response2) => { response2.pipe(file) .on("close", () => { console.log(`Generated PDF file saved as "${DestinationFile}" file.`); }); }); } else { // Service reported error console.log(data.message); } });}).on("error", (e) => { // Request error console.log(e);});// Write request datapostRequest.write(jsonPayload);postRequest.end();
import osimport requests # pip install requests# The authentication key (API Key).# Get your own by registering at https://app.pdf.coAPI_KEY = "******************************************"# Base URL for PDF.co Web API requestsBASE_URL = "https://api.pdf.co/v1"# Direct URL of source PDF file.# You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/ SourceFileURL = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-to-text/sample.pdf"# PDF document password. Leave empty for unprotected documents.Password = ""# Destination PDF file nameDestinationFile = ".\\result.pdf"def main(args = None): replaceStringFromPdf(SourceFileURL, DestinationFile)def replaceStringFromPdf(uploadedFileUrl, destinationFile): """Replace Text from PDF using PDF.co Web API""" # Prepare requests params as JSON parameters = {} parameters["name"] = os.path.basename(destinationFile) parameters["password"] = Password parameters["url"] = uploadedFileUrl parameters["searchString"] = "Your Company Name" parameters["replaceString"] = "XYZ LLC" # Prepare URL for 'Replace Text from PDF' API request url = "{}/pdf/edit/replace-text".format(BASE_URL) # Execute request and get response as JSON response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY }) if (response.status_code == 200): json = response.json() if json["error"] == False: # Get URL of result file resultFileUrl = json["url"] # Download result file r = requests.get(resultFileUrl, stream=True) if (r.status_code == 200): with open(destinationFile, 'wb') as file: for chunk in r: file.write(chunk) print(f"Result file saved as \"{destinationFile}\" file.") else: print(f"Request error: {response.status_code} {response.reason}") else: # Show service reported error print(json["message"]) else: print(f"Request error: {response.status_code} {response.reason}")if __name__ == '__main__': main()
package com.company;import com.google.gson.JsonObject;import com.google.gson.JsonParser;import okhttp3.*;import java.io.*;import java.net.*;import java.nio.file.Path;import java.nio.file.Paths;public class Main{ // The authentication key (API Key). // Get your own by registering at https://app.pdf.co final static String API_KEY = "***********************************"; // Direct URL of source PDF file. // You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/ final static String SourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-to-text/sample.pdf"; // PDF document password. Leave empty for unprotected documents. final static String Password = ""; // Destination PDF file name final static Path DestinationFile = Paths.get(".\\result.pdf"); public static void main(String[] args) throws IOException { // Create HTTP client instance OkHttpClient webClient = new OkHttpClient(); // Prepare URL for `Replace Text from PDF` API call String query = "https://api.pdf.co/v1/pdf/edit/replace-text"; // Make correctly escaped (encoded) URL URL url = null; try { url = new URI(null, query, null).toURL(); } catch (URISyntaxException e) { e.printStackTrace(); } // Create JSON payload String jsonPayload = String.format("{\"name\": \"%s\", \"password\": \"%s\", \"url\": \"%s\", \"searchString\": \"Your Company Name\", \"replaceString\": \"XYZ LLC\"}", DestinationFile.getFileName(), Password, SourceFileUrl); // Prepare request body RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonPayload); // Prepare request Request request = new Request.Builder() .url(url) .addHeader("x-api-key", API_KEY) // (!) Set API Key .addHeader("Content-Type", "application/json") .post(body) .build(); // Execute request Response response = webClient.newCall(request).execute(); if (response.code() == 200) { // Parse JSON response JsonObject json = new JsonParser().parse(response.body().string()).getAsJsonObject(); boolean error = json.get("error").getAsBoolean(); if (!error) { // Get URL of generated PDF file String resultFileUrl = json.get("url").getAsString(); // Download PDF file downloadFile(webClient, resultFileUrl, DestinationFile.toFile()); System.out.printf("Generated PDF file saved as \"%s\" file.", DestinationFile.toString()); } else { // Display service reported error System.out.println(json.get("message").getAsString()); } } else { // Display request error System.out.println(response.code() + " " + response.message()); } } public static void downloadFile(OkHttpClient webClient, String url, File destinationFile) throws IOException { // Prepare request Request request = new Request.Builder() .url(url) .build(); // Execute request Response response = webClient.newCall(request).execute(); byte[] fileBytes = response.body().bytes(); // Save downloaded bytes to file OutputStream output = new FileOutputStream(destinationFile); output.write(fileBytes); output.flush(); output.close(); response.close(); }}
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Cloud API asynchronous "Replace Text from PDF" job example (allows to avoid timeout errors).</title></head><body><?php // Cloud API asynchronous "Replace Text from PDF" job example.// The authentication key (API Key).// Get your own by registering at https://app.pdf.co$apiKey = "***********************************";// Direct URL of source PDF file. Check another example if you need to upload a local file to the cloud.// You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/ $sourceFileUrl = "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/pdf-to-text/sample.pdf";// PDF document password. Leave empty for unprotected documents.$password = "";// Prepare URL for `Replace Text from PDF` API call$url = "https://api.pdf.co/v1/pdf/edit/replace-text";// Prepare requests params$parameters = array();$parameters["password"] = $password;$parameters["url"] = $sourceFileUrl;$parameters["searchString"] = "Your Company Name";$parameters["replaceString"] = "XYZ LLC";$parameters["async"] = true; // (!) Make asynchronous job// Create Json payload$data = json_encode($parameters);// Create request$curl = curl_init();curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json"));curl_setopt($curl, CURLOPT_URL, $url);curl_setopt($curl, CURLOPT_POST, true);curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);curl_setopt($curl, CURLOPT_POSTFIELDS, $data);// Execute request$result = curl_exec($curl);if (curl_errno($curl) == 0){ $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($status_code == 200) { $json = json_decode($result, true); if (!isset($json["error"]) || $json["error"] == false) { // URL of generated PDF file that will available after the job completion $resultFileUrl = $json["url"]; // Asynchronous job ID $jobId = $json["jobId"]; // Check the job status in a loop do { $status = CheckJobStatus($jobId, $apiKey); // Possible statuses: "working", "failed", "aborted", "success". // Display timestamp and status (for demo purposes) echo "<p>" . date(DATE_RFC2822) . ": " . $status . "</p>"; if ($status == "success") { // Display link to the file with conversion results echo "<div><h2>Conversion Result:</h2><a href='" . $resultFileUrl . "' target='_blank'>" . $resultFileUrl . "</a></div>"; break; } else if ($status == "working") { // Pause for a few seconds sleep(3); } else { echo $status . "<br/>"; break; } } while (true); } else { // Display service reported error echo "<p>Error: " . $json["message"] . "</p>"; } } else { // Display request error echo "<p>Status code: " . $status_code . "</p>"; echo "<p>" . $result . "</p>"; }}else{ // Display CURL error echo "Error: " . curl_error($curl);}// Cleanupcurl_close($curl);function CheckJobStatus($jobId, $apiKey){ $status = null; // Create URL $url = "https://api.pdf.co/v1/job/check"; // Prepare requests params $parameters = array(); $parameters["jobid"] = $jobId; // Create Json payload $data = json_encode($parameters); // Create request $curl = curl_init(); curl_setopt($curl, CURLOPT_HTTPHEADER, array("x-api-key: " . $apiKey, "Content-type: application/json")); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Execute request $result = curl_exec($curl); if (curl_errno($curl) == 0) { $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($status_code == 200) { $json = json_decode($result, true); if (!isset($json["error"]) || $json["error"] == false) { $status = $json["status"]; } else { // Display service reported error echo "<p>Error: " . $json["message"] . "</p>"; } } else { // Display request error echo "<p>Status code: " . $status_code . "</p>"; echo "<p>" . $result . "</p>"; } } else { // Display CURL error echo "Error: " . curl_error($curl); } // Cleanup curl_close($curl); return $status;}?></body></html>