Inquiry about Adding Signature During Dynamic PDF Generation with GroupDocs.Signature

Hi Atir, is there any update on this?

This particular integration is an integral part of our project and we have to update further to our management so that we can purchase the product as soon as possible.
Regards, Nafi

@nafi1211

First and foremost thing is to understand how Signature API works.
Take a look at the code below:

using (Signature signature = new Signature("sample.pdf"))
{
    TextSignOptions options = new TextSignOptions("John Smith")
    {
        // set signature position
        Left = 100,
        Top = 100,
        // set signature rectangle
        Width = 100,
        Height = 30,
        // set Text color and Font
        ForeColor = Color.Red,
        Font = new SignatureFont { Size = 12, FamilyName = "Comic Sans MS" }
    };
    // sign document to file
    signature.Sign("sample_signed.pdf", options);
}

API takes a source file as input, then we set TextSignOptions (if we are going to do text signature), we specify signature position etc. And then save the output.
Now below are the guidelines, how to do this in WebForms. Obviously, you have to use some (your preferred) JS framework to handle client side.

Client side

<!-- Add this code in your ASP.NET WebForms page (.aspx) -->

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // Global variable to store the signature position
    var signaturePosition = { left: 0, top: 0 };

    // Function to capture the signature position
    function captureSignaturePosition(event) {
        // Get the coordinates relative to the PDF viewer container
        var containerOffset = $("#pdfViewerContainer").offset();
        var mouseX = event.pageX - containerOffset.left;
        var mouseY = event.pageY - containerOffset.top;

        // Store the signature position
        signaturePosition = { left: mouseX, top: mouseY };
    }

    // Attach click event to capture the signature position on PDF viewer click
    $(document).on("click", "#pdfViewerContainer", captureSignaturePosition);

    // Function to trigger the signature operation
    function signPDF() {
        // Send an AJAX request to the server-side API
        $.ajax({
            url: "SignatureAPI.ashx",
            method: "POST",
            data: {
                left: signaturePosition.left,
                top: signaturePosition.top
            },
            success: function (response) {
                // Handle the response from the server (e.g., display the signed PDF)
                // ...
            },
            error: function (xhr, status, error) {
                // Handle any error that occurred during the AJAX request
                // ...
            }
        });
    }
</script>

<!-- Add your PDF viewer container element -->
<div id="pdfViewerContainer">
    <!-- Display the PDF viewer here using your preferred PDF viewer libraries -->
</div>

<!-- Add a button to trigger the signature operation -->
<button type="button" onclick="signPDF()">Sign PDF</button>

Server side
Create a new Generic Handler (.ashx) file named “SignatureAPI.ashx” and add the following code:

using System;
using System.Drawing;
using System.IO;
using System.Web;

public class SignatureAPI : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        HttpRequest request = context.Request;

        // Retrieve the signature position from the request parameters
        int left = Convert.ToInt32(request.Form["left"]);
        int top = Convert.ToInt32(request.Form["top"]);

        // Retrieve the uploaded PDF file from the session or temporary storage
        byte[] pdfBytes = null;
        if (context.Session["UploadedPDF"] != null)
        {
            pdfBytes = (byte[])context.Session["UploadedPDF"];
            context.Session.Remove("UploadedPDF");
        }
        else
        {
            // Handle the case when the PDF file is not found
            // ...
            return;
        }

        // Save the PDF bytes to a temporary file
        string tempFilePath = Path.GetTempFileName() + ".pdf";
        File.WriteAllBytes(tempFilePath, pdfBytes);

        // Invoke your signature API here using the provided code snippet
        using (Signature signature = new Signature(tempFilePath))
        {
            TextSignOptions options = new TextSignOptions("John Smith")
            {
                Left = left,
                Top = top,
                Width = 100,
                Height = 30,
                ForeColor = Color.Red,
                Font = new SignatureFont { Size = 12, FamilyName = "Comic Sans MS" }
            };

            // Set the output file path for the signed PDF
            string outputFilePath = Path.GetTempFileName() + "_signed.pdf";

            // Sign the document
            signature.Sign(outputFilePath, options);

            // Return the signed PDF as the response
            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("Content-Disposition", "attachment; filename=signed.pdf");
            context.Response.TransmitFile(outputFilePath);
        }

        // Delete the temporary files
        File.Delete(tempFilePath);
        File.Delete(outputFilePath);
    }

    public bool IsReusable => false;
}

This basic example demonstrates how to capture the signature position on the client-side using JavaScript/jQuery and pass it to the server-side ASP.NET WebForms handler (SignatureAPI.ashx). The server-side code uses signature API logic to sign the PDF and returns the signed PDF as the response.
It’s up to you how you implement file upload, download and adjusting the PDF viewer logic but we have shared a sample code how API will work with WebForms.

Hello Atir,
Thanks for all the support from your side but the code you have provided works for text signatures as provided as “John Smith”


can you suggest me a way to add Digital Signatures instead of Text Signatures.
Regards Nafi

1 Like

@nafi1211

Good to know that the proposed solution worked for you. As far as digital signatures are concerned, please take a look at the following code:

using (Signature signature = new Signature("sample.pdf"))
{
    // initialize digital option with certificate file path
    DigitalSignOptions options = new DigitalSignOptions("certificate.pfx")
    {
        // set signature position
        Left = 100,
        Top = 100,
        Password = "1234567890"
    };
    signature.Sign("sampleSigned.pdf", options);
}

You just have to pass the digital certificate to the API, specify position and password.