This article explains how you can implement your own E-signature solution in C# using PDF.CO Web API.
In this digital era, more and more organizations are going paperless which highlights the need for implementing e-signature solutions. With PDF.CO Web API, you can replace specific texts with images. This also provides an opportunity to replace text with images containing e-signatures and this is what you will see in this article.
Here are the things we will cover:
- How to replace text in PDF documents with signature images from URLs;
- How to replace text in PDF with signature images uploaded from your local drive.
Replacing Text With Signature from a URL File
We will create a C# console application that shows how you can replace text with signature images from URLs.
The following script imports the required libraries for the scripts in this article.
using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq;
All the above libraries are by default installed with the Microsoft .NET framework except the Newtonsoft library. You can install the Newtonsoft library in the Microsoft Visual Studio IDE.
To install the Newtonsoft library, go to “Tools-> NuGet Package Manager”. Search for “Newtonsoft” library. You will see the following packages. Select the first package and click the “Install” button.
The sample PDF file in which we will replace text with a signature image can be downloaded from this link:
https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-sign/sample_affidavit.pdf
The first page of the source PDF file looks like this:
The above PDF file consists of two pages, and it has the text “[Your_Sign_Here]” at the bottom of both pages. We will replace this text with an image containing a signature. Let’s see how to do this.
The first step is to create variables that store the PDF.CO API Key, the URL for the source PDF file along with the file password, and the path to the destination PDF file. The following script does that.
const String API_KEY = "***********************"; const string SourceFile = @"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-sign/sample_affidavit.pdf"; const string DestinationFile = @".\newDocument.pdf"; const string Password = "";
Next, we will instantiate the C# WebClient class. The object of the WebClient class will be used to make calls to the PDF.CO Web API. The following script instantiates the WebClient class.
WebClient webClient = new WebClient(); webClient.Headers.Add("x-api-key", API_KEY);
The URL for the PDF.CO Web API call that replaces text with images is stored in a string variable as shown below:
string url = "https://api.pdf.co/v1/pdf/edit/replace-text-with-image";
The next step is important. We need to create a C# dictionary that stores parameter values that will be passed to the API call which replaces text with images.
In the script below, we create a parameter dictionary with the following parameters:
- name: which is the name of the destination PDF file
- password: the password of the source PDF file
- url: the url for the source PDF file
- searchString: the text that you want to replace with an image
- caseSensitive: setting it to false performs a case insensitive matching
- replaceImage: the url to the Image that you want to replace with the text in your pdf document.
Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("name", Path.GetFileName(DestinationFile)); parameters.Add("password", Password); parameters.Add("url", SourceFile); parameters.Add("searchString", "[Your_Sign_Here]"); parameters.Add("caseSensitive", "false"); parameters.Add("replaceImage", "https://sabo-pr.com/wp-content/uploads/2019/02/Mary-Ann-227x300.png");
To know more about the parameter values, check out the official API Documentation.
You need to serialize your parameter dictionary before you can pass it to the API call, as shown in the script below:
// Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters);
The rest of the script executes inside a try/catch block.
Inside the try/catch block, we make a call to the PDF.CO API using the “UploadString()” method of the WebClient class object.
The response from the API call is parsed as a JSON object. If the response contains an error, the error message is displayed on the console. Else, the URL of the destination PDF file is extracted and the PDF file is downloaded using the “DownloadFile()” method of the WebClient class object.
try { string response = webClient.UploadString(url, jsonPayload); JObject json = JObject.Parse(response); if (json["error"].ToObject<bool>() == false) { string resultFileUrl = json["url"].ToString(); Console.WriteLine(resultFileUrl); webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); }
Finally, you can destroy the WebClient class object by calling the “Dispose()” method as shown in the following script.
webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey();
Complete Code for Replacing Text With Signature
The complete code for replacing text with a signature image (from a URL) using the PDF.CO Web API in C# is as follows:
using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ByteScoutWebApiExample { class Program { const String API_KEY = "****************************"; const string SourceFile = @"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-sign/sample_affidavit.pdf"; const string DestinationFile = @".\newDocument.pdf"; const string Password = ""; static void Main(string[] args) { WebClient webClient = new WebClient(); webClient.Headers.Add("x-api-key", API_KEY); string url = "https://api.pdf.co/v1/pdf/edit/replace-text-with-image"; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("name", Path.GetFileName(DestinationFile)); parameters.Add("password", Password); parameters.Add("url", SourceFile); parameters.Add("searchString", "[Your_Sign_Here]"); parameters.Add("caseSensitive", "false"); parameters.Add("replaceImage", "https://sabo-pr.com/wp-content/uploads/2019/02/Mary-Ann-227x300.png"); // Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters); try { string response = webClient.UploadString(url, jsonPayload); JObject json = JObject.Parse(response); if (json["error"].ToObject<bool>() == false) { string resultFileUrl = json["url"].ToString(); Console.WriteLine(resultFileUrl); webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); } } }
Our input PDF document looks like this.
The destination PDF document is as follows. You can see that the text [Your_Sign_Here] is replaced by a signature image.
Replacing Text with Signatures from an Uploaded File
In this section, you will see how to replace text in a PDF document with an image stored locally on your drive. The idea will be similar to replacing text with an image from a URL, however, you will see how to upload a local image to PDF.CO cloud storage and then use its URL to replace the image with text in a PDF document.
So let’s begin without ado.
The following script stores in string variables, the API key, the URL to the source PDF file along with its password, and the path to the destination file.
const String API_KEY = "************************"; const string SourceFile = @"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-sign/sample_affidavit.pdf"; const string SignFile = @".\sign_image.JPG"; const string DestinationFile = @".\newDocument.pdf"; const string Password = "";
The following script creates a WebClient class object for making requests to PDF.CO Web API.
WebClient webClient = new WebClient(); webClient.Headers.Add("x-api-key", API_KEY);
The next step is to upload the local image that contains a signature, from your hard drive.
The following script uses the WebClient class object to fetch the URL from the PDF.CO cloud storage. Your local image will be uploaded to that URL.
string query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}", Path.GetFileName(SignFile))); string response = webClient.DownloadString(query); JObject json = JObject.Parse(response); string uploadUrl = json["presignedUrl"].ToString(); string uploadedFileUrl = json["url"].ToString();
And the following script calls the PDF.CO Web API to actually upload the image to the PDF.CO cloud storage.
webClient.Headers.Add("content-type", "application/octet-stream"); webClient.UploadFile(uploadUrl, "PUT", SignFile); webClient.Headers.Remove("content-type"); string url = "https://api.pdf.co/v1/pdf/edit/replace-text-with-image";
The rest of the process is similar to what you saw in the previous section. You need to create a parameter dictionary containing information that will be passed to the PDF.CO Web API call. The dictionary is also serialized as shown below:
Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("name", Path.GetFileName(DestinationFile)); parameters.Add("password", Password); parameters.Add("url", SourceFile); parameters.Add("searchString", "[Your_Sign_Here]"); parameters.Add("caseSensitive", "false"); parameters.Add("replaceImage", uploadedFileUrl); // Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters);
Next, in the try/catch block the WebClient class object makes a call to the PDF.CO Web API that replaces text with an image. The response is parsed as a JSON object.
In case the response contains an error, the error message is printed. Else, using the URL returned in the response object, the destination PDF file is downloaded locally.
try { response = webClient.UploadString(url, jsonPayload); json = JObject.Parse(response); if (json["error"].ToObject<bool>() == false) { string resultFileUrl = json["url"].ToString(); Console.WriteLine(resultFileUrl); webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); }
Finally, the WebClient class object is destroyed as shown below:
webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey();
Source Code for Replacing Text With Signature
The complete code for replacing text in a PDF document with an image uploaded from a local hard drive is as follows:
using System; using System.Collections.Generic; using System.IO; using System.Net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace ByteScoutWebApiExample { class Program { const String API_KEY = "usmanmalik57@gmail.com_8df5671cedb0fb37ec9610eada409f110c38"; const string SourceFile = @"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-sign/sample_affidavit.pdf"; const string SignFile = @".\sign_image.JPG"; const string DestinationFile = @".\newDocument.pdf"; const string Password = ""; static void Main(string[] args) { WebClient webClient = new WebClient(); webClient.Headers.Add("x-api-key", API_KEY); string query = Uri.EscapeUriString(string.Format( "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name={0}", Path.GetFileName(SignFile))); string response = webClient.DownloadString(query); JObject json = JObject.Parse(response); string uploadUrl = json["presignedUrl"].ToString(); string uploadedFileUrl = json["url"].ToString(); webClient.Headers.Add("content-type", "application/octet-stream"); webClient.UploadFile(uploadUrl, "PUT", SignFile); webClient.Headers.Remove("content-type"); string url = "https://api.pdf.co/v1/pdf/edit/replace-text-with-image"; Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("name", Path.GetFileName(DestinationFile)); parameters.Add("password", Password); parameters.Add("url", SourceFile); parameters.Add("searchString", "[Your_Sign_Here]"); parameters.Add("caseSensitive", "false"); parameters.Add("replaceImage", uploadedFileUrl); // Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters); try { response = webClient.UploadString(url, jsonPayload); json = JObject.Parse(response); if (json["error"].ToObject<bool>() == false) { string resultFileUrl = json["url"].ToString(); Console.WriteLine(resultFileUrl); webClient.DownloadFile(resultFileUrl, DestinationFile); Console.WriteLine("Generated PDF file saved as \"{0}\" file.", DestinationFile); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); } } }
From the output below, you can see that the text is replaced with an image of a signature.