DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Trending

  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • What Is Plagiarism? How to Avoid It and Cite Sources
  • How to Convert XLS to XLSX in Java
  • A Developer's Guide to Mastering Agentic AI: From Theory to Practice
  1. DZone
  2. Coding
  3. Frameworks
  4. Creating a Signature Pad Using Canvas and ASP.NET Core Razor Pages

Creating a Signature Pad Using Canvas and ASP.NET Core Razor Pages

HTML5 enables developers to do a lot these days. In this post, we'll see just how powerful it can be when combined with the ASP.NET Core Razor Pages framework.

By 
Juergen Gutsch user avatar
Juergen Gutsch
·
Jun. 11, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
28.1K Views

Join the DZone community and get the full member experience.

Join For Free

In one of our projects, we needed to add the possibility to add signatures to PDF documents. A technician fills out a checklist online and a responsible person and the technician need to sign the checklist afterward. The signatures then get embedded into a generated PDF document together with the results of the checklist. The signatures must be created on a web UI, running on an iPad Pro.

It was pretty clear that we needed to use the HTML5 canvas element and to capture the pointer movements. Fortunately, we stumbled upon a pretty cool library on GitHub, created by Szymon Nowak from Poland. It is the super awesome Signature Pad written in TypeScript and available as an NPM and Yarn package. It is also possible to use a CDN to use the Signature Pad.

Use Signature Pad

Using Signature Pad is really easy and works well without any configuration. Let me show you in a quick way how it works.

To play around with it, I created a new ASP.NET Core Razor Pages web using the dotnet CLI:

dotnet new razor -n SignaturePad -o SignaturePad 

I added a new razor page called Signature and added it to the menu in the _Layout.cshtml. I created a simple form and placed some elements in it:

<form method="POST">
    <p>
        <canvas width="500" height="400" id="signature" 
                style="border:1px solid black"></canvas><br>
        <button type="button" id="accept" 
                class="btn btn-primary">Accept signature</button>
        <button type="submit" id="save" 
                class="btn btn-primary">Save</button><br>
        <img width="500" height="400" id="savetarget" 
             style="border:1px solid black"><br>
        <input type="text" asp-for="@Model.SignatureDataUrl"> 
    </p>
</form>

The form posts the content to the current URL, which is the same Razor page, but a different HTTP method handler. We will have a look later on.

The canvas is the most important thing. This is the area where the signature gets drawn. I added a border to make the pad boundaries visible on the screen. I add a button to accept the signature. This means we lock the canvas and write the image data to the input field added as the last element. I also added a second button to submit the form. The image is just to validate the signature and is not really needed, but I was curious about how it looks in an image tag.

This is not the nicest HTML code but works for a quick test.

Right after the form, I added a script area to render the JavaScript to the end of the page. To get it running quickly, I use jQuery to access the HTML elements. I also copied the signature_pad.min.js into the project, instead of using the CDN version:

@section Scripts{
    <script src="~/js/signature_pad.min.js"></script>
    <script>
        $(function () {

            var canvas = document.querySelector('#signature');
            var pad = new SignaturePad(canvas);

            $('#accept').click(function(){

                var data = pad.toDataURL();

                $('#savetarget').attr('src', data);
                $('#SignatureDataUrl').val(data);
                pad.off();

            });

        });
    </script>
}

As you can see, creating the Signature Pad is simply done by creating a new instance of SignaturePad and passing the canvas as an argument. After clicking the accept button, I start working with the pad. The function toDataURL() generates an image data URL that can be directly used as an image source like I do in the next line. After that, I store the result as a value in the input field to send it to the server. In production, this should be a hidden field. At the end, I switch the Signature Pad off to lock the canvas and the user cannot manipulate the signature anymore.

Handling the Image Date URL With C#

The image data URL looks like this:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAfQAAAGQCAYA... 

So after the comma, the image is a base 64 encoded string. The data before the comma describes the image type and the encoding. I now send the complete data URL to the server and we need to decode the string.

public void OnPost()
{
    if (String.IsNullOrWhiteSpace(SignatureDataUrl)) return;

    var base64Signature = SignatureDataUrl.Split(",")[1];            
    var binarySignature = Convert.FromBase64String(base64Signature);

    System.IO.File.WriteAllBytes("Signature.png", binarySignature);
}

On the page model, we need to create a new method, OnPost(), to handle the HTTP POST method. Inside we first check whether the bound property has a value or not. Then we split the string with a comma and convert the base 64 string to a byte array.

With this byte array, we can do whatever we need to do. In the current project, I store the image directly in the PDF and in this demo I just store the data in an image on the hard drive.

Conclusion

As mentioned, this is just a quick demo with some ugly code. But the rough idea could be used to make it better in Angular or React. To learn more about Signature Pad visit the repository.

This example also shows what is possible with HTML5 these days. I really like the possibilities of HTML5 and the HTML5 APIs used with JavaScript.

Hope this helps!

ASP.NET ASP.NET Core

Published at DZone with permission of Juergen Gutsch, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Developing Minimal APIs Quickly With Open Source ASP.NET Core
  • Revolutionizing Content Management

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!