# Digital Signature

DsPdf is a Document Solutions product that offers a rich library to read, create, modify, and save PDF files without using any external tool.

## Content

A digital signature is an electronic, encrypted, stamp of authentication on PDF documents to secure the authenticity of the content. The signature confirms that the information was created by the signer and has not been tampered with. DsPdfViewer enables a user to digitally sign a PDF document and save it to the server using an optional save settings parameter **sign** of **SignatureInfo** type in the client-side **save** method. This method is used to specify signature settings to digitally sign a PDF document. The signing is implemented on the server side.
The client-side save method sends a request to the server to save the document with a signature. The server side signing is implemented using the following two events: **VerifyAuthToken** and **OnSign**. The VerifyAuthToken validates the authentication token, while the onSign event adds the signature to the PDF document after verifying it with the certificate.
Refer to the example code below, which implements server side signing by binding the events and defining the event handlers in the Startup.cs file:

```csharp
public class Startup {

    const int MAX_MESSAGE_SIZE = 268435456/*256MB*/;

    static Startup() {
        Licensing.AddLicenseKeys();
    }

    // Configure the DsPdfViewer.
    public void Configuration(IAppBuilder app) {
        app.UseCors(CorsOptions.AllowAll);
        GcPdfViewerHub.Configure(app);
        GcPdfViewerController.Settings.VerifyToken += VerifyAuthToken;
        GcPdfViewerController.Settings.Sign += OnSign;

    }

    // Validate the authentication token provided during DsPdfViewer initialization.
    private void VerifyAuthToken(object sender, VerifyTokenEventArgs e) {
            string token = e.Token;
        if (string.IsNullOrEmpty(token) || !token.StartsWith("support-api-demo")) {
            e.Reject = true;
        }
    }

    // Implement PDF document server side signing.
    private void OnSign(object sender, SignEventArgs e) {
        var signatureProperties = e.SignatureProperties;

            string projectRootPath = HttpContext.Current.Server.MapPath("~");
            string certificatePath = Path.Combine(projectRootPath, "assets/DsPdfTest.pfx");
        byte[] certificateBytes = File.ReadAllBytes(certificatePath);
        if (certificateBytes == null) {
            e.Reject = true;
            return;
        }
            X509Certificate2 certificate = new X509Certificate2(
            certificateBytes, "qq", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
        signatureProperties.SignatureBuilder = new GrapeCity.Documents.Pdf.Pkcs7SignatureBuilder()
        {
            CertificateChain = new X509Certificate2[] { certificate },
            HashAlgorithm = GrapeCity.Documents.Pdf.Security.OID.HashAlgorithms.SHA512,
                Format = GrapeCity.Documents.Pdf.Pkcs7SignatureBuilder.SignatureFormat.adbe_pkcs7_detached
        };

            string fontPath = Path.Combine(projectRootPath, "assets/arialuni.ttf");
        signatureProperties.SignatureAppearance = new SignatureAppearance
        {
            TextFormat = new TextFormat
            {
                Font = Font.FromFile(fontPath),
                    FontSize = 5.5f
            }
        };
    }

}
```

Refer to the following example code to digitally sign a PDF document:

```javascript
// Specify the signature settings.
viewer.save(undefined, { sign: { signatureField: "Employee", signerName: "Employee Name", location: locationName }, reload: true });
```

DsPdfViewer's save method also provides an optional parameter **saveMode** which is used to save a PDF document using incremental update or as linearized.
Refer to the following example code to save a PDF document using incremental update:

```javascript
viewer.save("IncrementalUpdate.pdf", { saveMode: "IncrementalUpdate" });
```

For more information on how to add a digital signature, see [Sign document using digital signature](https://developer.mescius.com/documents-api-pdfviewer/demos/signatures/digital-signature/sign-with-digital-signature).

> !type=note
> **Note:** SupportApi should be configured in order to digitally sign a PDF document, and it is only available with the Professional License of DsPdfViewer. For more information, see [Configure Server-Based PDF Editor](/document-solutions/dot-net-pdf-api/docs/online/pdfviewer/edit-pdf/configure-pdf-editor).

## Get Signature Information

DsPdfViewer enables a user to check if a PDF document is digitally signed. DsPdfViewer provides a **getSignatureInfo** client-side method to acquire all the information about the signatures available in the PDF document. The following example codes depict the various scenarios in which this method can be used.
Refer to the following example code to acquire an array of all signature fields available in the PDF document, irrespective of whether they are signed or not:

```javascript
const signatureInfo = await viewer.getSignatureInfo();
```

Refer to the following example code to check if a PDF document is signed:

```javascript
const signatureInfo = await DsPdfViewer.findControl("#viewer").getSignatureInfo();
console.log(signatureInfo.signed ?
    "The document is signed with digital signature." : "The document is not signed");
```

Refer to the following example code to iterate through all the signature fields available in the PDF document:

```javascript
const info = await DsPdfViewer.findControl("#viewer").getSignatureInfo();
for (const field of info.signatureFields) {
    console.log("Field '" + field.fieldName + "', has signature value: " + !!field.signatureValue);
}
```

Refer to the following example code to show information about all signatures used in the PDF document:

```javascript
var viewer = DsPdfViewer.findControl("#root");
const signatureInfo = await viewer.getSignatureInfo();
if (signatureInfo.signed) {
    let s = "";
    for (let i = 0; i < signatureInfo.signedByFields.length; i++) {
        const signedField = signatureInfo.signedByFields[i], signatureValue = signedField.signatureValue;
        const signerName = signatureValue.name, location = signatureValue.location,
            signDate = viewer.pdfStringToDate(signatureValue.modificationDate).toDateString();
        s += `${i + 1}. Signed by field: ${signedField.fieldName}, signer name: ${signerName}, location: ${location}, sign date: ${signDate}\n`;
    }
    alert("The document was signed using digital signature:\n" + s);
} else {
    alert("The document is not signed.");
}
```