Allow your users to add their handwritten signature inside an HTML editor with Telerik UI for ASP.NET AJAX.
In today’s world, where digitization has taken over every aspect of our lives, the need for signatures has not been eliminated. However, now instead of physically signing a document, we can use an electronic signature, which is quick, easy and secure. One popular way of doing this is to use a handwritten signature, which gives the electronic document a personal touch.
Progress Telerik UI for ASP.NET AJAX provides two useful components, RadSignature and RadEditor, that can be integrated to facilitate the inclusion of handwritten signatures to an HTML editor.
In this blog post, I will showcase how to build a custom Signature dialog application scenario that integrates RadSignature and RadEditor. The demo allows users to insert a handwritten signature into a content area of the RadEditor.
The WYSIWYG editor control has a custom button called “Insert Handwritten Signature.” When clicked upon, it opens a dialog box that displays a signature pad. The user can leverage the signature pad to draw their signature. Once done, they can click on the “Store on Server as PNG and Insert” button to store the signature on the server as a PNG file and insert the signature image into the editor.
Let’s take a look at the code that makes this possible.
The default.aspx page contains the RadEditor control with the custom button defined inside the tool groups.
ASPX code snippet (HTML)
<telerik:RadEditor RenderMode="Lightweight" runat="server" ID="RadEditor1" Width="800px">
<Tools>
<telerik:EditorToolGroup>
<telerik:EditorTool Name="InsertSignature" Text="Insert Handwritten Signature"></telerik:EditorTool>
</telerik:EditorToolGroup>
<telerik:EditorToolGroup>
<telerik:EditorTool Name="Bold"></telerik:EditorTool>
<telerik:EditorTool Name="Italic"></telerik:EditorTool>
<telerik:EditorTool Name="Underline"></telerik:EditorTool>
</telerik:EditorToolGroup>
</Tools>
<Content>
To sign up, simply click on the pencil icon above and use your mouse to handwrite your signature and insert it here.
</Content>
</telerik:RadEditor>
<script>
// Add custom command to the RadEditor command list
Telerik.Web.UI.Editor.CommandList['InsertSignature'] = function (commandName, editor, args) {
// Callback function to handle signature insertion after the dialog is closed
var myCallbackFunction = function (sender, args) {
// Insert signature image HTML into the editor
editor.pasteHtml(String.format('<img src=\'{0}\' border=\'0\' style=\'width:50%;height:50%;\' /> ', args.src));
};
// Show signature dialog as an external dialog
editor.showExternalDialog(
'InsertSignature.aspx',
null,
540,
450,
myCallbackFunction,
null,
'Draw and Insert Signature',
true,
Telerik.Web.UI.WindowBehaviors.Close + Telerik.Web.UI.WindowBehaviors.Move,
false,
true);
};
</script>
The script placed below the editor declaration adds a custom command to the RadEditor command list. It shows the signature dialog as an external dialog, loads it with the InsertSignature.aspx page, and handles the signature insertion after the dialog is closed.
To style the custom button and visualize a font-icon over it add the following CSS class:
CSS snippet
.reTool.reInsertSignature.reToolIcon:before {
content: "\e10b";
}
The InsertSignature.aspx page contains a RadSignature control that provides the signature pad functionality. The RadButton1 button stores the signature on the server as a PNG file and inserts the signature image into the editor. The RadAjaxManager1 control handles the AJAX request and updates the RadSignature1 control.
ASPX (InsertSignature.aspx)
<telerik:RadAjaxManager EnableAJAX="true" ID="RadAjaxManager1" runat="server" OnAjaxRequest="RadAjaxManager1_AjaxRequest">
<ClientEvents OnResponseEnd="OnResponseEnd" />
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="RadButton1">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="RadSignature1" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
<ClientEvents OnResponseEnd="insertEmoticon" />
</telerik:RadAjaxManager>
<telerik:RadButton runat="server" ID="RadButton1" Text="Store on Server as PNG and Insert" AutoPostBack="false" OnClientClicked="sendToServer" />
<br />
<br />
<telerik:RadSignature runat="server" ID="RadSignature1" Height="270" Width="400">
<ClientEvents OnLoad="signatureLoad" />
</telerik:RadSignature>
<telerik:RadScriptBlock runat="server" ID="RadScriptBlock1">
<script>
var signature;
var fileName = "signature.png";
function signatureLoad(sender, args) {
signature = sender;
}
function sendToServer(sender, args) {
if (!signature.get_value()) return;
var ajaxManager = $find("<%= RadAjaxManager1.ClientID %>");
ajaxManager.ajaxRequest(fileName + ";" + signature.get_value());
}
//called when the OnResponseEnd of RadAjaxManager fires
function insertSignatureImage(sender, args) {
signature.set_value('');
var closeArgument = {};
//asign the imageSrc which comes from the server to the src argument
closeArgument.src = imageSrc;
//closes the dialog and submit the src to the myCallbackFunction function on the main page
getRadWindow().close(closeArgument);
}
</script>
</telerik:RadScriptBlock>
In the section below, we continue discussing the code behind the signature dialog, and more specifically the server-side code that handles the AJAX request and saves the signature as a PNG file on the server.
C# (InsertSignature.aspx.cs)
protected void RadAjaxManager1_AjaxRequest(object sender, Telerik.Web.UI.AjaxRequestEventArgs e)
{
// Split the argument received into two parts, separated by a semicolon.
var args = e.Argument.Split(new[] { ';' }, 2);
// Get the filename from the first part of the argument.
var fileName = args[0];
// Get the base64-encoded image data from the second part of the argument and extract the image string
var base64raw = args[1];
var base64data = base64raw.Split(',')[1];
// Check if the size of the received data does not exceed 200KB and is a valid base64 image.
var isSizeValid = (Encoding.UTF8.GetByteCount(base64raw) < 200000);
var isImageString = base64raw.StartsWith("data:image/png;base64");
// If the received data is a valid image string, save the image to disk.
if (isImageString && isSizeValid)
{
// Generate a unique filename by appending a GUID to the original filename.
var fileNameGuid = Guid.NewGuid() + "_" + fileName;
// Get the full path to the images folder and append the unique filename to it.
var path = Server.MapPath("~/Editor/Examples/SignatureDialog/Images") + "\\" + fileNameGuid;
// Convert the base64 data to bytes and write it to the specified path.
System.IO.File.WriteAllBytes(path, Convert.FromBase64String(base64data));
// Create a script to be registered with the page that sets the image source to the saved image file.
string script = string.Format("var imageSrc ='Images/" + fileNameGuid + "';");
// Register the script with the page so that the imageSrc gets available in the insertEmoticon client function
ScriptManager.RegisterStartupScript(Page, typeof(Page), "myscript", script, true);
}
}
Let’s go through the code above.
The RadAjaxManager1_AjaxRequest
event handler is where the magic happens. This handler is called when the “Store on Server as PNG and Insert” button is clicked. The e.Argument
parameter tells us what the purpose of the AJAX request is. In
this case, the value will be the image file name and the base64 data coming from the exported signature drawing.
We start by getting the signature image from the RadSignature control as a byte array. We then generate a random file name with a .png extension and save the signature image as a PNG file on the server. Note that we are saving the image to a folder called “Images” in the root of our application. You can change this folder to one of your preference.
Next, we construct a RegisterStartupScript
response to return the path for the saved signature image to the main page. We use the ScriptManager.RegisterStartupScript
method to add JavaScript code to the callback function on the main page. This code calls
the insertSignatureImage
function on the main page, passing the path to the saved signature image as a parameter.
The insertSignatureImage
is also responsible for inserting the signature image into the RadEditor’s content area at cursor position.
In this blog post, we have showcased how to integrate the RadSignature and RadEditor for Telerik UI fo ASP.NET AJAX components to provide a signature pad dialog that allows users to insert a handwritten signature into a content area of the editor. We have discussed the code for the main page and the signature dialog, as well as the server-side code that handles the AJAX request and saves the signature as a PNG file on the server.
I hope you have found this blog post useful and informative. If you have any questions or feedback, please leave a comment below. Thank you for reading and happy coding!
Want to start taking advantage of the ASP.NET AJAX RadEditor and RadSignature components, or any of the other 120+ ready-made controls, like the Grid or the Scheduler? Start a free trial today and experience for yourself that building Web Forms apps for any browser and device in half the time is a piece of cake.
Rumen Jekov (@Rumen_Jekov) started his career at Telerik’s ASP.NET team in 2004 as a tech support engineer and passed through the position of a team lead to a product manager. He has answered more than 51,500 tickets helping customers to achieve their goals. Presently, he is a product owner of Telerik UI for ASP.NET AJAX and a manager of the AJAX crew at Progress. Off work, he enjoys traveling across the globe, watching movies and tech shows, reading books and listening to podcasts.