Collect and Save Electronic Signatures

A client of ours needed to collect electronic signatures from their users. A quick search led me to the fantastic signature_pad project that Szymon Nowak posted to GitHub. In no time, I had the example running and was drawing all sorts of goofy signatures.

It wasn’t complicated, but it would have been even easier if there was a ready-built example to start from. Here I’m sharing that ready-built example that I couldn’t find. Hopefully it’ll save others some time.

Before we get too far along, here’s the signature pad that we’re talking about:

Isn’t that cool? The one above doesn’t actually save, but you can build your own that does in just a couple minutes by creating these three files…

First, we have the HTML file that the signature pad is housed on. Start with a blank HTML5 page, give it a title, and add in the form and signature input pad:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Signature Pad</title>
</head>
<body>

<form id="signature-form" action="save.php" method="post">

<canvas id="signature-canvas" style="width:500px;height:200px;max-width:100%;border:1px #CCC solid;"></canvas>

<div id="signature-message"></div>

<div id="signature-buttons">
	<input type="button" id="clear-signature-btn" value="Clear"> 
	<input type="button" id="save-signature-btn" value="Save">
</div>

<input type="hidden" name="signature" id="signature-data" value="">

</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/signature_pad/1.5.3/signature_pad.min.js"></script>
<script src="example.js"></script>

</body>
</html>

This example has a “clear” button too. That’s handy. Without it, your user has no way of clearing the pad and starting over.

You’ll notice we call two JavaScript files. The first is a CDN version of the signature_pad core. The second, example.js, is a collection of stuff that’ll make our particular example work. Here’s what it contains:

var clearButton = document.getElementById('clear-signature-btn'),
	savePNGButton = document.getElementById('save-signature-btn'),
	canvas = document.getElementById('signature-canvas'),
	signaturePad;

function resizeCanvas() {
	var ratio =  Math.max(window.devicePixelRatio || 1, 1);
	canvas.width = canvas.offsetWidth * ratio;
	canvas.height = canvas.offsetHeight * ratio;
	canvas.getContext("2d").scale(ratio, ratio);
}

window.onresize = resizeCanvas;
resizeCanvas();

signaturePad = new SignaturePad(canvas);

clearButton.addEventListener('click', function (event) {
	signaturePad.clear();
});

savePNGButton.addEventListener('click', function (event) {
	if (signaturePad.isEmpty()) {
		alert('Signature pad is blank. Please draw your signature.');
	} else {
		var sdata = signaturePad.toDataURL();
		document.getElementById('signature-data').value = sdata;
		document.getElementById('signature-form').submit();
	}
});

Hopefully, that’s fairly self-explanatory. If not, either check out the original example and its notes (as much of the logic came from there) or leave a comment below.

This next part is where the magic happens. We take the data generated by the signature pad and store it as a PNG image file on our PHP server, then display it to the user. This is save.php that the form points to:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Signature Pad</title>
</head>
<body>

<?php

$dir = './signatures/'; //the folder to place your signature files in
$file = $dir.'signature_'.time().'.png'; //the filename of your new signature

if (empty($_POST['signature'])) {
	echo '<p>Error: No signature submitted!</p>';
} else {
	$data = trim(strip_tags($_POST['signature']));
	if (substr($data,0,15) != 'data:image/png;') { echo '<p>Error: Invalid signature file!</p>'; }
	else {
		$encoded_image = explode(',',$data)[1];
		$decoded_image = base64_decode($encoded_image);
		file_put_contents($file,$decoded_image) or die('<p>Error: Could not save file.</p>');
		echo '<p>Your signature was saved successfully as '.$file.'.</p>';
		echo '<p><img src="'.$file.'" alt="signature"></p>';
	}
}

?>

</body>
</html>

Don’t forget to create the directory you specify in $dir. And make sure it’s writeable!

This is a very simplified example. Obviously, you’d want to add in some security checks along the way. But this should at least get you started. Happy signature-ing!


Comments

Loading…

This post was published on August 18th, 2017 by Robert James Reese in the following categories: JavaScript and PHP. Before using any of the code or other content in this post, you must read and agree to our terms of use.