Sign PDF with C#

This guide will assist you in integrating DocuSeal document e-signing capabilities into your C# application. With DocuSeal, you can create document templates from your PDF files, send them to the signers, and receive signed copies. Templates can be created either using our web UI or through the API. For instance, you can design a document template with various field types using HTML and CSS or PDF upload. More information on this can be found in our guides.

How to sign PDFs with C#

  • Create a DocuSeal account and obtain an API key.
  • Create a document template using web UI or API.
  • Send a document signing request by specifying the template and information about the signers. Alternatively, embed a signing form on your website.
  • Manage signed documents in your DocuSeal account or utilize our webhooks for process automation.

Obtaining an Authorization Token

Before you begin making requests to our API, you need to obtain an authorization token so that we can identify you and your API requests.

To do this, you should register on our website if you haven't already and obtain an authorization token via Developer Console. The authorization token will look something like this:

ET6sBznGN42bTMEaNMkzAa

Sending a Signing Request

DocuSeal allows you to sign a document by one or multiple signatories. Each signing request is referred to as a "submission", and each signatory is called a "submitter". Let's take a look at an example of sending a signing request to one signatory.

You can send signing requests using an HTTP POST request to the address:

https://api.docuseal.com/submissions

In the request body, you should specify the following:

  • template_id - the template identifier
  • send_email - send email invitations for signing
  • submitters - an array of submitters

Each submitter should contain:

  • role - the role of the submitter
  • email - the email address of the submitter

Here's an example of how to create a submission using the RestSharp library:

using RestSharp;
using Newtonsoft.Json;

public class Submission
{
    public long TemplateId { get; set; }
    public bool SendEmail { get; set; }
    public Submitter[] Submitters { get; set; }
}

public class Submitter
{
    public string Role { get; set; }
    public string Email { get; set; }
}

var submission = new Submission
{
    TemplateId = 1000001,
    SendEmail = true,
    Submitters = new[]
    {
      new Submitter { Role = "First Party", Email = "john.doe@example.com" }
    }
};

var client = new RestClient("https://api.docuseal.com/submissions");
var request = new RestRequest(Method.POST);
request.AddHeader("X-Auth-Token", "API_KEY"); // Replace with your API key
request.AddHeader("content-type", "application/json");

string jsonBody = JsonConvert.SerializeObject(submission);

request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

Console.WriteLine(response.Content);

DocuSeal API has many other parameters that you can use for sending signing requests. In this guide, we will only cover the most basic example so you can understand how it works. For more detailed information, you can refer to our documentation.

Embedded Signing Form

In the previous example, we used the API to send a signing request, but sometimes you may not have the opportunity to use the API or the DocuSeal web UI. Also, you may not always know the email of the signer, but you do know that they have visited your website. In such cases, you can use an embedded Signing form. This allows you to embed a Signing form on your website so that the signer can sign the document directly on your website. To embed the Signing form, you need to create a document template in our web UI or using our API and use the unique template ID.

Let's integrate a signing form into our web page using plain JavaScript for this example. To do this, you need to add the following code to your page:

<script src="https://cdn.docuseal.com/js/form.js"></script>
  • data-src - is a unique URL of the template, which you can obtain from the DocuSeal control panel after creating the template or by using the API.
  • completed - is an event that will be called after the document is successfully signed.
<script src="https://cdn.docuseal.com/js/form.js"></script>

<docuseal-form
  id="docusealForm"
  data-src="https://docuseal.com/d/LEVGR9rhZYf86M"> <!-- Unique template URL -->
</docuseal-form>

<script>
  window.docusealForm.addEventListener('completed', (e) => e.detail)
</script>

After adding this code to your page, you will see such a signing form on your website. However, you can customize its appearance and behavior using many parameters. You can read more about this in our documentation.

https://yourwebsite.com

Processing Sign Results Using Webhooks

After the signer has signed the document, DocuSeal can send you the sign results using a webhook. You can use these results to process the sign in your application. For example, you can save the signed document in your application. To do this, you need to specify the address of your server, to which we will send the sign results. You can do this in the webhooks settings.

DocuSeal can send you 3 types of webhooks:

  • form.viewed - when the signer first views the Signing form
  • form.started - when the signer starts filling out the Signing form
  • form.completed - when all signers have completed filling out the Signing form

Let's consider an example when the signer has completed filling out the Signing form, and a webhook has been sent to your server. To do this, you need to create a webhook handler on your server that will process the sign results.

In this example, we use the ASP.NET Core library to handle the webhook payload and save the signed PDFs to the local file system.

public class WebhookPayload
{
    public string EventType { get; set; }
    public WebhookData Data { get; set; }
}

public class WebhookData
{
    public List<WebhookDocument> Documents { get; set; }
}

public class WebhookDocument
{
    public string Url { get; set; }
    public string Name { get; set; }
}
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using System.Linq;

[Route("api/[controller]")]
[ApiController]
public class WebhookController : ControllerBase
{
    private readonly IHttpClientFactory _clientFactory;

    public WebhookController(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }

    [HttpPost]
    public async Task<IActionResult> Post(WebhookPayload payload)
    {
        if (payload.EventType == "form.completed" && payload.Data?.Documents != null)
        {
            foreach (var document in payload.Data.Documents)
            {
                var client = _clientFactory.CreateClient();
                var response = await client.GetAsync(document.Url);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsByteArrayAsync();
                    var savePath = Path.Combine(Directory.GetCurrentDirectory(), "saved_files", document.Name + ".pdf");

                    Directory.CreateDirectory(Path.GetDirectoryName(savePath));

                    await System.IO.File.WriteAllBytesAsync(savePath, content);
                    Console.WriteLine($"Document saved to: {savePath}");
                }
            }

            return Ok();
        }

        return BadRequest("Invalid event type or missing documents");
    }
}

Conclusions

In this guide, we have only covered the most basic example of using DocuSeal in a C# application. DocuSeal has many other capabilities that you can use to enhance your application. For example, you can embed not only the Signing form on your website but also the Form builder. You can also use the API to fully automate the process of generating custom documents using HTML and then sending them for signer without using the DocuSeal web UI. Additionally, you can host DocuSeal on your own server to gain the full ownership and control over your data.