Articles in this section
Category / Section

How to add date time in handwritten signature in Angular PDF Viewer?

9 mins read
Description:

This article demonstrates how to add a date and time stamp to handwritten signatures in the Syncfusion Angular PDF Viewer. The implementation shows how to automatically include a timestamp when a user adds a signature to a PDF document.

Solution:

The solution involves capturing the signature add event and modifying the signature to include the current date and time. This is accomplished by using HTML canvas to combine the signature with a timestamp before adding it to the document.

Prerequisites:

Before proceeding with the implementation, ensure that the following steps are completed:

  1. Syncfusion PDF Viewer Setup: Ensure the Syncfusion PDF Viewer is installed and set up in your Angular project. Follow the Getting Started guide for Syncfusion PDF Viewer for Angular if you haven’t already.
  2. Basic Knowledge of Angular: Familiarity with Angular components and lifecycle hooks, especially ngOnInit, will help you follow along with the implementation.
Code Snippets
Create the PDF Viewer Component

In your component’s HTML file app.component.html, set up the PDF Viewer element to display the PDF document:

<div class="control-section">
    <div class="content-wrapper">
        <ejs-pdfviewer #pdfviewer id="pdfViewer" 
            [documentPath]='document' 
            [resourceUrl]='resource' 
            (addSignature)='SignatureAdded($event)' 
            style="height:640px;display:block">
        </ejs-pdfviewer>
    </div>
</div>
Implement Signature Handling in Your Component

Add the signature handling logic in app.component.ts to automatically include datetime information.

import { Component, ViewEncapsulation, ViewChild } from '@angular/core';
import {
  PdfViewerComponent,
  LinkAnnotationService,
  BookmarkViewService,
  MagnificationService,
  ThumbnailViewService,
  ToolbarService,
  NavigationService,
  TextSearchService,
  TextSelectionService,
  PrintService,
  AnnotationService,
  FormFieldsService,
  FormDesignerService,
  PageOrganizerService,
  AddSignatureEventArgs,
  HandWrittenSignatureSettings,
  DisplayMode,
} from '@syncfusion/ej2-angular-pdfviewer';
import { SwitchComponent } from '@syncfusion/ej2-angular-buttons';

/**
 * Default PdfViewer Controller
 */
@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  encapsulation: ViewEncapsulation.None,
  providers: [
    LinkAnnotationService,
    BookmarkViewService,
    MagnificationService,
    ThumbnailViewService,
    ToolbarService,
    NavigationService,
    TextSearchService,
    TextSelectionService,
    PrintService,
    AnnotationService,
    FormFieldsService,
    FormDesignerService,
    PageOrganizerService,
  ],
  styleUrls: ['app.component.css']
})
export class AppComponent {
  @ViewChild('pdfviewer')
  public pdfviewerControl: PdfViewerComponent | undefined;
  @ViewChild('switch')
  public switch: SwitchComponent | undefined;

  public document: string =
    'https://cdn.syncfusion.com/content/pdf/pdf-succinctly.pdf';
  public resource: string =
    'https://cdn.syncfusion.com/ej2/23.2.6/dist/ej2-pdfviewer-lib';

  // Flag to track if signature has been added
  private signatureAddedFlag: boolean = false;

  ngOnInit(): void {
    // ngOnInit function
  }

  public SignatureAdded(args: AddSignatureEventArgs): void {
    if (this.signatureAddedFlag) {
      this.signatureAddedFlag = false;
      return; // Exit if signature has already been added
    }

    let id = '';
    let proxy = this;
    console.log(args);
    if (id !== args.id) {
      id = args.id;
    }

    if (
      args.type === 'HandWrittenSignature' ||
      args.type === 'SignatureImage'
    ) {
      // Set the flag to true, indicating that a signature is being added
      this.signatureAddedFlag = true;
      var c: any = document.createElement('canvas');
      c.width = 300;
      c.height = 150;
      var ctx = c.getContext('2d');

      // Load the signature image
      var image = new Image();
      image.onload = function () {
        ctx.drawImage(image, 0, 0, 300, 150);
        var date = new Date().toLocaleDateString();
        ctx.font = 'italic 18px Arial';
        ctx.fillStyle = 'blue';
        ctx.fillText(date, 10, 140);
        var imagedata = c.toDataURL('image/png');
        console.log(imagedata);
        var signatureCollections: any =
          proxy.pdfviewerControl?.signatureCollection;
        for (var x = 0; x < signatureCollections.length; x++) {
          if (signatureCollections[x].annotationId === args.id) {
            var left = args.bounds.left;
            var top = args.bounds.top;
            var width = args.bounds.width;
            var height = args.bounds.height;

            signatureCollections[x].signatureType = 'Image';
            signatureCollections[x].value = imagedata;
            proxy.pdfviewerControl?.annotation.deleteAnnotationById(args.id);
            proxy.pdfviewerControl?.annotation.addAnnotation(
              'HandWrittenSignature',
              {
                offset: { x: left, y: top },
                pageNumber: 1,
                width: width,
                height: height,
                signatureItem: ['Signature'],
                signatureDialogSettings: {
                  displayMode: DisplayMode.Upload,
                  hideSaveSignature: false,
                },
                canSave: false,
                path: imagedata,
              } as HandWrittenSignatureSettings
            );
          }
        }
      };
      if (args.data) {
        image.src = args.data; // Set the image source with null check
      } else {
        console.error('Signature data is undefined');
      }
    } else if (args.type === 'SignatureText') {
      this.signatureAddedFlag = true;
      var signatureCollections: any =
        proxy.pdfviewerControl?.signatureCollection;
      for (var x = 0; x < signatureCollections.length; x++) {
        if (signatureCollections[x].annotationId === args.id) {
          const signatureText = args.data;
          const date = new Date().toLocaleDateString();
          const updatedValue = signatureText + '\n' + date;
          signatureCollections[x].signatureType = 'Text';
          signatureCollections[x].value = updatedValue;
          var left = args.bounds.left;
          var top = args.bounds.top;
          var width = args.bounds.width;
          var height = args.bounds.height;
          var canvas: any = document.createElement('canvas');
          canvas.width = width;
          canvas.height = height;
          var ctx = canvas.getContext('2d');
          ctx.font = 'normal 16px Arial';
          ctx.fillStyle = 'black';
          ctx.textAlign = 'left';
          ctx.fillText(signatureText, 10, 30);
          ctx.font = 'italic 14px Arial';
          ctx.fillStyle = 'blue';
          ctx.fillText(date, 10, 60);
          var imageData = canvas.toDataURL('image/png');
          proxy.pdfviewerControl?.annotation.deleteAnnotationById(args.id);
          proxy.pdfviewerControl?.annotation.addAnnotation(
            'HandWrittenSignature',
            {
              offset: { x: left, y: top },
              pageNumber: 1,
              width: width,
              height: height,
              signatureItem: ['Signature'],
              signatureDialogSettings: {
                displayMode: DisplayMode.Upload,
                hideSaveSignature: false,
              },
              canSave: false,
              path: imageData,
            } as HandWrittenSignatureSettings
          );
        }
      }
    } else {
      id = '';
    }
  }
}
Key Features Used in the Code:
  1. Event Handling: The addSignature event is used to capture when a signature is added to the document.
  2. HTML Canvas: Canvas is used to combine the original signature with a timestamp.
  3. Different Signature Types:
    • HandWrittenSignature/SignatureImage: Draw the signature image on a canvas and add the date/time text.
    • SignatureText: Create a canvas and add both the signature text and date/time with different styling.
  4. Custom Styling: The timestamp is displayed in a different font style (italic) and color (blue) to distinguish it from the signature.
Sample:

You can find the full sample in our GitHub repository.

Conclusion

I hope you enjoyed learning how to add date time in handwritten signature in Angular PDF Viewer.

You can refer to Angular PDF Viewer feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Angular PDF Viewer example to understand how to create and manipulate data.

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, BoldDesk Support, 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