Articles in this section
Category / Section

How to integrate Digital signature in ASP.NET MVC PDF Viewer?

3 mins read

PDF Viewer

The ASP.NET MVC PDF Viewer control supports viewing, reviewing, and printing PDF files in ASP.NET MVC applications. The hyperlink and table of contents support provides easy navigation within and outside the PDF files. The form-filling support provides a platform to fill, flatten, save, and print PDF files with AcroForm. PDF files can be reviewed with text markup annotation tools.

Integrating Digital Signature

Currently, PDF viewer does not support Digital Signature, but you can integrate Digital Signature in the PDF viewer control.

The following code illustrates how to upload the PdfCertificate(.pfx) file on the ‘PageClick’ event of the PDF viewer and send the uploaded file to the Server side using Ajax request.

JavaScript

   <script type="text/javascript">
        var xPos= null;
        var yPos= null;
        var jsonResult = new Object();
        document.getElementById('fileUpload').addEventListener('change', readFile, false);
       // Uploads the digital signature
        function readFile(evt) {
            var upoadedFiles = evt.target.files;
            var uploadedFile = upoadedFiles[0];
            var reader = new FileReader();
            reader.readAsDataURL(uploadedFile);
            reader.onload = function () {
         //Sends the uploaded data as base64 string, X-Coordinate, Y-Coordinate and Page Number to the sever side using the Ajax request
                var obj = $("#pdfviewer").data("ejPdfViewer");
                var uploadedFileUrl = this.result;
                jsonResult["pageNum"] = obj._currentPage;
                jsonResult["sign"] = (this.result).split(",")[1];
                jsonResult["xPos"] = xPos;
                jsonResult["yPos"] = yPos;
                jsonResult["id"] = obj._fileId;
                $.ajax({
                    url: '../api/PdfViewer/SignatureDownload',
                    method: 'POST',
                   crossDomain: true,
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    data: JSON.stringify(jsonResult),
                    traditional: true,
                    success: function (data) {
                         alert(data);
                    },
                    error: function (jqXHR, textStatus) {
                        alert("Request failed: " + textStatus);
                    }
                });
            }
        }
          $(function () {
               //Hooks the pageClick event to the PDF Viewer
               var _ejPdfViewer = $("#pdfviewer").data("ejPdfViewer");
                _ejPdfViewer.model.pageClick = "pageClicked";
            });
            function pageClicked(sender) {
                xPos = sender.XCoordinate;
                yPos = sender.YCoordinate;
                var _ejPdfViewer = $("#pdfviewer").data("ejPdfViewer");
               $('#fileUpload').click();
                }
    </script>

The following code illustrates how to integrate the uploaded Digital Signature file with the PDF document.

C#

public object SignatureDownload(Dictionary<string, string> jsonResult)
        {
            PdfViewerHelper helper = new PdfViewerHelper();           
            object pdfData = (object)helper.GetDocumentData(jsonResult);              
            //Gets the X Coordinate, Y coordinate and Page number from the Json data            
            var x = JsonConvert.DeserializeObject<float>(jsonResult["xPos"]);
            var y = JsonConvert.DeserializeObject<float>(jsonResult["yPos"]);
            var pageNum = JsonConvert.DeserializeObject<float>(jsonResult["pageNum"]);
            byte[] byteArray = Convert.FromBase64String(jsonResult["sign"]);
            MemoryStream stream = new MemoryStream(byteArray);
            //storing the .pfx file locally.                                                        File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/Data/PDFsign.pfx"), byteArray);
          //Get the document stream as base64 string            
           var propertyInfo = pdfData.GetType().GetProperty("documentStream");
            string value = propertyInfo.GetValue(pdfData, null).ToString();
            byte[] byteContents = Convert.FromBase64String(value);
            MemoryStream memoryStreams = new MemoryStream(byteContents);
            //load the document again for including the signature.
            PdfLoadedDocument pdfldoc = new PdfLoadedDocument(memoryStreams);
            PdfLoadedPage page = pdfldoc.Pages[(int)pageNum-1] as PdfLoadedPage;
            PdfSignatureField signatureField = new PdfSignatureField(page, "SignatureField");
           //Adding bounds for the signature field.
            signatureField.Bounds = new RectangleF((float)x, (float)y, 100, 100);
            signatureField.Signature = new PdfSignature();
            //Adds certificate to the signature field.
            signatureField.Signature.Certificate = new PdfCertificate(HttpContext.Current.Server.MapPath("~/Data/PDFsign.pfx"), "syncfusion");           
            signatureField.Signature.Reason = "I am author of this document";
            //Adds the field.
            pdfldoc.Form.Fields.Add(signatureField);
            //Saves the certified PDF document in Data folder.
           pdfldoc.Save(HttpContext.Current.Server.MapPath("~/Data/Output.pdf"));                        
           pdfldoc.Close(true);
            string output ="Document is saved in " + HttpContext.Current.Server.MapPath("~/Data");
            return output;                  
        }

Sample link:

Find the sample for integrating the Digital Signature to the PDF viewer control from https://www.syncfusion.com/downloads/support/directtrac/general/ze/Sample1094583529

The previous sample uploads the Digital Signature(PdfCertificate(.pfx)) on the ‘PageClick’ event of the PDF Viewer and sends the uploaded file to the server side using the Ajax request. In the server side the digital signature is added to the PDF document as a signature field using the Syncfusion Pdf library, then the PDF document along with the signature is saved locally in the server side.


Conclusion

I hope you enjoyed learning about how to integrate Digital signature in PDF Viewer.

You can refer to our ASP.NET MVC 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 ASP.NET MVC 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 forumsDirect-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 sign in to leave a comment
Access denied
Access denied