Capturing signature is very important for many business use cases specifically for Salesforce community portals where we get agreement signed by customers. There are many contract management application available for this in AppExchange , in this post we will generate and create signature in LWC.
I have already posted a article long back which is for lightning aura component for similar functionality. You can check blog Create Signature Pad in Salesforce Lightning, if you are looking for aura version.
For creating signature component in LWC, I have added two use cases in this blog, generating signature using some custom signature font and creating our signature manually. let us how to create a LWC which will handle both use cases.
Steps for creating LWC
Download and Upload custom font
Create LWC for generating Signature
Create Apex class to upload signature
Add functionality to capturing Signature in LWC
1. Download and Upload custom font
For this blog, I have used GreatVibes-Regular and upload in static resource as signature. You can put all font files in one folder and zip it with name signature
2. Create LWC for generating Signature
After custom font uploaded in static resource, we can use this to generate signature automatically for given text. Let use create LWC component signatureCanvas to generate and create signature. In this step let us code for generating signature using font.
Add css class in LWC component and add above style code to load font for component. Give resource path based on your uploaded content. In my case signature is static resource name and GreatVibes-Regular.ttf is font filename.
Now we have to generate signature text using above font, for this use below code. Below event handler code will use custom font while writing text. fillText function will add text on canvas.
var signText = e.detail.value;
ctx.font = "30px GreatVibes-Regular";
ctx.fillText(signText, 30, canvasElement.height/2);
We can download generated signature also. To download below code will be used,
var link = document.createElement('a');
link.download = '.jpg';
link.href = dataURL;
This code will downloads as JPEG format. For other format, change format in above code.
3. Create Apex class to upload signature
Create a apex class which will upload signature in salesforce record attachement. It will store attachment in Salesforce files.
4. Add functionality to capturing Signature in LWC
User can sign manually also so let us add functionality to create signature in this component.
User can sign on canvas, so we have to draw text on canvas using path and strokes method. stroke method draw a path or shape. Path methods like moveTo , LineTo help in creating some shape.
I have created one API property in JS to add header text on signature panel. based on your requirement, add/remove properties.
Complete LWC Code:
5. Test LWC
LWC component is ready to test now, we can use it in lightning record page. Add this component using lightning page builder.