Articles in this section
Category / Section

How to create a custom signature pad to sign PDFs in PDF Viewer?

6 mins read

This article demonstrates how to integrate a custom signature dialog using Syncfusion SignaturePad to capture and add handwritten signatures into a PDF document using the Syncfusion MAUI PDF Viewer.

Prerequisites

  • A .NET MAUI project set up.
  • The Syncfusion PDF Viewer NuGet package is installed.

Step 1: Install Required NuGet Package

To get started, create a new Maui app and ensure the following package is installed in your .NET MAUI project:

Syncfusion.Maui.PdfViewer

You can install this package using the NuGet Package Manager or the NuGet CLI.

Step 2: Initialize the PDF Viewer in XAML

Start by adding the Syncfusion PDF Viewer control to your XAML file.

a. Add the Syncfusion namespace in your MainPage.xaml:

Define the XAML namespace to enable access to the PDF Viewer.

XAML

xmlns:syncfusion="clr-namespace:Syncfusion.Maui.PdfViewer;assembly=Syncfusion.Maui.PdfViewer"

b. Add the PDF Viewer control to your layout:

Initialize the SfPdfViewer in the XAML file. This will display the PDF Viewer in your app. You can load any PDF document into this Viewer.

XAML

<syncfusion:SfPdfViewer x:Name="pdfViewer" ShowToolbars="False" Grid.Row="1"/>

c. Load the PDF in the PDF Viewer control:

Load the PDF document as an embedded resource using the DocumentSource API in the PDF Viewer.

C#

Stream? PdfDocumentStream = this.GetType().Assembly.GetManifestResourceStream("CustomSignatureDialog.Assets.handwritten-signature.pdf");
FileData = new PdfFileData("handwritten-signature.pdf", PdfDocumentStream);

XAML:

  <syncfusion:SfPdfViewer x:Name="pdfViewer" DocumentSource="{Binding FileData.Stream}"  
  Tapped="PdfViewerTapped"
  ShowToolbars="False"
  ShowScrollHead="False"/>

Step 3: Create Custom Signature Dialog

a. Add Required Namespace:

In your .cs file (e.g., MainPage.xaml.cs), you need to import the Syncfusion SignaturePad namespace to use the signature control. This gives access to the SfSignaturePad control, which allows the user to draw a signature.

C#

using Syncfusion.Maui.SignaturePad;

b. Design the Signature Pad Layout:

Create a Grid layout that acts as a pop-up for drawing the signature. This layout includes:

  • A label (“Draw Signature”) to indicate what the user should do.
  • A signature pad for drawing the signature.
  • Three buttons:
    • Close– to cancel the dialog
    • Clear– to erase and redraw
    • Create– to save the signature

Then define row and column sizes to control layout positioning and appearance, set the background color, and adjust the width based on device type.

C#

Grid signatureLayout = new Grid
{
    HeightRequest = 500,
    RowDefinitions = {
        new RowDefinition { Height = 50 },
        new RowDefinition { Height = GridLength.Star },
        new RowDefinition { Height = 50 }
    },
    ColumnDefinitions = {
        new ColumnDefinition { Width = GridLength.Star },
        new ColumnDefinition { Width = GridLength.Star },
        new ColumnDefinition { Width = GridLength.Star }
    },
    BackgroundColor = Colors.Lavender,
    HorizontalOptions = LayoutOptions.Center,
    VerticalOptions = LayoutOptions.Center,
    Padding = new Thickness(5, 0),
    WidthRequest = DeviceInfo.Idiom == DeviceIdiom.Phone
        ? DeviceDisplay.MainDisplayInfo.Width / DeviceDisplay.MainDisplayInfo.Density
        : 500
};

c. Add Controls to the Layout:

Create each UI control programmatically:

  • The Label tells the user to “Draw Signature”.
  • The Close Button closes the dialog.
  • The Clear Button clears the signature pad.
  • The Create Button extracts the drawn signature.
  • The SfSignaturePad itself is used for drawing.

Then position these controls in the grid using Grid.SetRow and Grid.SetColumn, and finally add them to the layout.

C#

Label drawLabel = new Label { Text = "Draw Signature", HorizontalOptions = LayoutOptions.Center };
Button closeButton = new Button { Text = "Close", BackgroundColor = Color.FromArgb("#6750A4") };
Button clearButton = new Button { Text = "Clear", BackgroundColor = Color.FromArgb("#6750A4") };
Button createButton = new Button { Text = "Create", BackgroundColor = Color.FromArgb("#6750A4"), TextColor = Colors.White };
SfSignaturePad signaturePad = new SfSignaturePad { Background = Colors.White };

// Set grid positions
Grid.SetRow(drawLabel, 0); Grid.SetColumn(drawLabel, 1);
Grid.SetRow(closeButton, 0); Grid.SetColumn(closeButton, 2);
Grid.SetRow(signaturePad, 1); Grid.SetColumnSpan(signaturePad, 3);
Grid.SetRow(clearButton, 2); Grid.SetColumn(clearButton, 0);
Grid.SetRow(createButton, 2); Grid.SetColumn(createButton, 2);

// Add controls to the layout
signatureLayout.Children.Add(drawLabel);
signatureLayout.Children.Add(closeButton);
signatureLayout.Children.Add(signaturePad);
signatureLayout.Children.Add(clearButton);
signatureLayout.Children.Add(createButton);

// Add to main container (e.g., Grid named 'signatureContainer')
signatureContainer.Children.Add(signatureLayout);

d. Handle Button Events:

Each button has a specific action:

  • Close: Hides the signature pad dialog.
  • Clear: Clears the signature pad for a fresh start.
  • Create: Does the most important work:
    • Converts the drawn signature into an image.
    • Resizes the image to a consistent dimension (max 150px).
    • Saves the resulting image stream so it can be added to the PDF.
    • If signing a form filling document, checks if signatureFormField is not null and adds the signature as an ink annotation by setting the IsSignature property to true using the points collection from the signature pad.

C#

closeButton.Clicked += (s, e) => signatureLayout.IsVisible = false;
clearButton.Clicked += (s, e) => signaturePad.Clear();

createButton.Clicked += (s, e) =>
{
    if (signatureView is SfSignaturePad signature) // Ensure valid instance of signature pad is used
    {
      var inkPoints = signature?.GetSignaturePoints() ?? new List<List<float>>(); // Gather points constituting the signature
      if (signatureFormField != null)
      {
         // For form fields, convert ink points to an ink annotation
         int pageNumber = signatureFormField.PageNumber;
         InkAnnotation ink = new InkAnnotation(inkPoints, pageNumber);
         ink.IsSignature = true;
         ink.Color = Colors.Black;
         ink.BorderWidth = 2;
         signatureFormField.Signature = ink; // Add ink annotation to the form field
      }
      else
      {
         // Convert drawn signature to an image source if no form field
         ImageSource? imagestream = signature?.ToImageSource();
         if (imagestream is StreamImageSource streamsource)
         {
             var stream = await streamsource.Stream(CancellationToken.None); // Get the stream for the image source
             stream.Position = 0; // Reset position in the stream
             Microsoft.Maui.Graphics.IImage platformImage = Microsoft.Maui.Graphics.Platform.PlatformImage.FromStream(stream);
             imageWidth = platformImage.Width;
             imageHeight = platformImage.Height;

             // Scale the image dimensions proportionately if they exceed limits
             if (imageWidth < imageHeight)
             {
                 if (imageWidth > 150)
                 {
                     imageHeight = 150 * (imageHeight / imageWidth);
                     imageWidth = 150;
                 }
             }
             else
             {
                 if (imageHeight > 150)
                 {
                     imageWidth = 150 * (imageWidth / imageHeight);
                     imageHeight = 150;
                 }
             }
             stream.Position = 0; // Reset stream position
             signatureStream = stream; // Retain stream for annotation
          }
          ShowToast("Tap to add signature"); // Alert user to place signature
      }
      signatureFormField = null; // Clear form field reference after use
      signatureView?.Clear(); // Clear the signature pad
      if (signaturelayout != null)
         signaturelayout.IsVisible = false; // Hide the dialog after creating signature
      signatureButton.IsVisible = true; // Show signature button for further interaction
    }
 };

Step 4: Integrate with PDF Viewer

a. Enable Signature Annotation Mode:

To enable signature mode in SfPdfViewer, set the AnnotationMode property to Signature. This activates the signature functionality and opens the signature dialog. You can implement this behavior in the event handler for the signature button click.

C#

private void OnSignatureButtonClicked(object sender, EventArgs e)
{
    pdfViewer.AnnotationMode = AnnotationMode.Signature;
}

b. Override the Built-in Signature Modal:

To display a custom signature pad instead of the built-in dialog, handle the SignatureModalViewAppearing event. In the event handler, suppress the default signature dialog and set the custom signature layout’s visibility to true. Store the SignatureFormField to add the signature later when signing the form-filling document.
C#

// Event for suppressing the built-in signature dialog.
pdfViewer.SignatureModalViewAppearing += PdfViewer_SignatureModalViewAppearing;

// Handle the custom signature dialog visibility in the event handler.
 private void PdfViewer_SignatureModalViewAppearing(object? sender, FormFieldModalViewAppearingEventArgs e)
 {
      e.Cancel = true; // Cancel default dialog
      if (e.FormField != null && e.FormField is SignatureFormField formField)
      {
          signatureFormField = formField; // Store form field for signature placement
      }
      if (signaturelayout != null)
      {
         signaturelayout.IsVisible = true; // Show custom signature dialog
         signatureButton.IsVisible = false; // Hide signature button
      }
 }

c. Add signature to PDF:

To add a signature at the tapped position in the PDF, handle the Tapped event of the PDF Viewer. Retrieve the tapped position, create a stamp annotation using the previously stored signature stream, and set its IsSignature property to true to mark it as a signature annotation. Finally, add it to the PDF.

C#:

 private void PdfViewerTapped(object sender, GestureEventArgs e)
 {
     if (signatureStream != null)
     {
         // Create a stamp annotation using the drawn signature's stream
         StampAnnotation stamp = new StampAnnotation(signatureStream, e.PageNumber, new RectF(e.PagePosition.X - imageWidth / 2, e.PagePosition.Y - imageHeight / 2, imageWidth, imageHeight));
         stamp.IsSignature = true; // Mark as signature annotation
         pdfViewer.AddAnnotation(stamp); // Add annotation to the PDF
         signatureStream = null; // Clear the stream to prevent reuse
     }
 }

Step 5 : Run the app

Finally, run your app. After the PDF is loaded in the viewer:

  • Click the Signature button in the PDF Viewer.

  • Your custom signature dialog will appear.

  • Draw your signature using the SfSignaturePad.

  • Tap Create to finalize the signature.

  • Then, tap on the desired position in the PDF to place the signature.

Output :

CustomSignatureDialog.gif

Sample link:
View sample in GitHub

Conclusion

I hope you found this guide helpful in learning how to create a custom signature pad for adding handwritten signatures to a PDF document in your application.

You can refer to our MAUI PDFViewer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied