# Create SignFabric Envelopes from Mail Merge Templates in .NET C#

> This article explains how to use TX Text Control to mail merge JSON data into a document template and submit the merged document to the SignFabric API. It shows how your own application can create an envelope workflow by sending the document, signer metadata, and workflow options through the API.

- **Author:** Bjoern Meyer
- **Published:** 2026-06-23
- **Modified:** 2026-06-23
- **Description:** This article explains how to use TX Text Control to mail merge JSON data into a document template and submit the merged document to the SignFabric API. It shows how your own application can create an envelope workflow by sending the document, signer metadata, and workflow options through the API.
- **9 min read** (1705 words)
- **Tags:**
  - ASP.NET
  - ASP.NET Core
  - SignFabric
  - eSignatures
  - MailMerge
- **Web URL:** https://www.textcontrol.com/blog/2026/06/23/create-signfabric-envelopes-from-mail-merge-templates-using-dotnet-csharp/
- **LLMs URL:** https://www.textcontrol.com/blog/2026/06/23/create-signfabric-envelopes-from-mail-merge-templates-using-dotnet-csharp/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2026/06/23/create-signfabric-envelopes-from-mail-merge-templates-using-dotnet-csharp/llms-full.txt
- **GitHub Repository:** https://github.com/TextControl/TXTextControl.SignFabric.APICall

---

Document signing workflows often start before the signing application is opened. A business system already knows the customer, contract details, line items, dates, and recipient information. In that scenario, the signing process should be started by an integration: Generate the document, create the envelope, and route it to the correct signers.

This article shows how a .NET console application can use TX Text Control to merge JSON data into a document template and then submit the resulting document to the SignFabric API. The sample represents the role of your own application: It owns the data, creates the document, and starts the envelope workflow without requiring a manual upload step.

> **Automated Envelope Creation**
> 
> The integration pattern is simple: Merge the document in your own application, authenticate against SignFabric, and send the generated document plus recipient metadata to the envelope API.
> 
> <https://github.com/TextControl/SignFabric>

### The Integration Flow

The sample console application follows a typical server-side integration flow:

1. Load a TX Text Control template from disk.
2. Load JSON data for the mail merge process.
3. Use MailMerge.MergeJsonData to merge the data into the template.
4. Save the merged document in TX internal format.
5. Request an API access token.
6. Post the merged document and signer metadata to the envelope API.

This keeps document generation and envelope creation in one automated process. The calling system does not need to ask users to upload the finished document manually after the merge.

### Template and JSON Data

The template contains regular merge fields for business data and TX signature fields for the signers. The JSON file contains the values that are merged into the document.

```
[
    {
        "contract_date": "2020-01-01",
        "provider": {
            "name": "Service Provider LLC",
            "contact": {
                "name": "John Doe",
                "title": "CEO"
            }
        },
        "client": {
            "name": "Client LLC",
            "contact": {
                "name": "Jane Doe",
                "title": "CFO"
            }
        }
    }
]
```

The following template shows the starting point for the integration: Merge fields are populated from JSON data, while the signature boxes define where SignFabric recipients will sign.

![TX Text Control template with merge fields and signature boxes](https://s1-www.textcontrol.com/assets/dist/blog/2026/06/23/a/assets/template.webp "TX Text Control template with merge fields and signature boxes")

The document template can use these values in merge fields and merge blocks. After the merge, the resulting document is saved as .tx, which is one of the supported upload formats configured in SignFabric.

### Merging the Document

The console application uses ServerTextControl as a non-visual document processing component. The template is loaded into ServerTextControl, connected to MailMerge, and merged with JSON data.

```
using var tx = new ServerTextControl();
tx.Create();

var loadSettings = new LoadSettings {
    ApplicationFieldFormat = ApplicationFieldFormat.MSWordTXFormFields
};

tx.Load(templateBytes, BinaryStreamType.InternalUnicodeFormat, loadSettings);

using var mailMerge = new TXTextControl.DocumentServer.MailMerge {
    TextComponent = tx,
    RemoveEmptyFields = false
};

mailMerge.MergeJsonData(jsonData);

tx.Save(out byte[] mergedDocument, BinaryStreamType.InternalUnicodeFormat);
```

In a production integration, the template could come from a database, blob storage, a template repository, or another business application. The important part is that the final byte array is posted to SignFabric as a Base64 encoded document.

### Signer IDs and Signature Fields

SignFabric validates that every signer in the API request has a matching signature field in the document. The rule is simple and explicit:

```
signer id "provider" requires signature field "txsign_provider"
signer id "client" requires signature field "txsign_client"
```

This relationship is important because it connects the API recipient list to the physical signature boxes in the document. If the request contains a signer with the ID customer, but the document contains only txsign\_provider and txsign\_client, the API rejects the envelope.

The sample therefore validates the merged document before submitting it. It reads the signature field names and compares them with the configured signer IDs. This catches configuration issues locally and prints a useful message before the API call is made.

```
var requiredSignatureNames = signers
    .Select(signer => "txsign_" + signer.Id)
    .ToList();

var documentSignatureNames = tx.SignatureFields
    .Cast<SignatureField>()
    .Select(field => field.Name)
    .Where(name => !string.IsNullOrWhiteSpace(name))
    .ToHashSet(StringComparer.OrdinalIgnoreCase);

var missingSignatureNames = requiredSignatureNames
    .Where(name => !documentSignatureNames.Contains(name))
    .ToList();

if (missingSignatureNames.Count > 0) {
    throw new InvalidOperationException(
        "The merged document does not contain matching signature fields for all signers." +
        Environment.NewLine +
        "Required signature fields: " + string.Join(", ", requiredSignatureNames) +
        Environment.NewLine +
        "Found signature fields: " + string.Join(", ", documentSignatureNames));
}
```

```
The merged document does not contain enough signature fields for the configured signers.
Required signature fields: txsign_customer, txsign_sales
Found signature fields: txsign_provider, txsign_client
```

After adjusting the configured signers to provider and client, the same document passes validation and can be submitted to SignFabric.

### Requesting an Access Token

The SignFabric API is protected by bearer authentication. For first-party integrations, SignFabric includes a local OAuth client-credentials endpoint:

[/api/v1/oauth/token ](https://github.com/TextControl/SignFabric/blob/master/Controllers/LocalOAuthController.cs)

The console application sends a standard client credentials request:

```
grant_type=client_credentials
client_id=sf_...
client_secret=sfsecret_...
scope=envelopes:create envelopes:read
```

The token endpoint accepts form encoded values or JSON. The important parameters are:

- grant\_type: Must be client\_credentials.
- client\_id: The API client identifier configured in SignFabric.
- client\_secret: The secret generated for the API client.
- scope: A space-separated list of requested API scopes, such as envelopes:create envelopes:read.

The token is then attached to the envelope API request as a bearer token.

```
using var response = await httpClient.PostAsync(
    "api/v1/oauth/token",
    new FormUrlEncodedContent(new Dictionary<string, string> {
        ["grant_type"] = "client_credentials",
        ["client_id"] = clientId,
        ["client_secret"] = clientSecret,
        ["scope"] = "envelopes:create envelopes:read"
    }));

response.EnsureSuccessStatusCode();

var token = await response.Content.ReadFromJsonAsync<TokenResponse>();
httpClient.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", token.AccessToken);
```

### Creating the Envelope

The merged document is submitted to the SignFabric envelope endpoint:

[/api/v1/envelopes ](https://github.com/TextControl/SignFabric/blob/master/Controllers/EnvelopeIntegrationApiController.cs)

The request includes the file name, the Base64 encoded document, the signer list, an optional signing certificate ID, and whether the envelope should be sent immediately.

```
var request = new CreateEnvelopeApiRequest {
    FileName = "merged-envelope.tx",
    DocumentBase64 = Convert.ToBase64String(mergedDocument),
    SendImmediately = true,
    Signers = new List<CreateEnvelopeSignerApiRequest> {
        new() {
            Id = "provider",
            Name = "John Doe",
            Email = "john.doe@example.com"
        },
        new() {
            Id = "client",
            Name = "Jane Doe",
            Email = "jane.doe@example.com"
        }
    }
};

using var response = await httpClient.PostAsJsonAsync("api/v1/envelopes", request);
response.EnsureSuccessStatusCode();

var envelope = await response.Content.ReadFromJsonAsync<CreateEnvelopeApiResponse>();
Console.WriteLine($"Envelope created: {envelope.EnvelopeId}");
```

The envelope endpoint expects a JSON body with the following values:

- fileName: The document name stored with the envelope. The extension must be allowed by the SignFabric upload policy.
- documentBase64: The merged document as a Base64 encoded string.
- signers: The recipient list for the envelope. Each signer requires an id, name, and email.
- signingCertificateId: Optional certificate ID used for the final signed PDF.
- sendImmediately: Optional flag that controls whether the envelope is submitted immediately after creation.

When sendImmediately is set to true, SignFabric creates the envelope, validates the signature boxes, sends the signing invitations, and returns the resulting envelope status.

```
{
  "success": true,
  "envelopeId": "180afbd0-d8f6-47c1-bf0f-d2d62508762f",
  "name": "merged-envelope.tx",
  "status": "Sent",
  "containsSignatureBoxes": true,
  "signers": [
    {
      "id": "provider",
      "name": "John Doe",
      "status": "Sent"
    },
    {
      "id": "client",
      "name": "Jane Doe",
      "status": "Sent"
    }
  ]
}
```

After the API call succeeds, the generated document appears as a regular SignFabric envelope with the configured recipients and workflow status.

![Created envelope in SignFabric](https://s1-www.textcontrol.com/assets/dist/blog/2026/06/23/a/assets/signfabric-envelope.webp "Created envelope in SignFabric")

### Authentication for API Calls

Before an application can create envelopes, it needs an access token that is accepted by the SignFabric API. In local or first-party integration scenarios, this can be done with the built-in client credentials endpoint. In production environments, the same envelope call can be protected by the configured bearer authentication setup.

From the perspective of the calling application, the token request is a setup step before creating the envelope. The envelope creation itself remains independent of where the document was generated or where the business data came from.

### Running the Sample

The console sample is configured with an appsettings.sample.json file that contains the SignFabric URL, local OAuth client credentials, template path, JSON data path, output path, and signer list.

```
dotnet build
dotnet run -- --config appsettings.sample.json
```

The client secret can also be supplied through an environment variable so it does not need to be stored in the sample configuration file:

```
$env:SIGNFABRIC_CLIENT_SECRET = "<client-secret>"
dotnet run -- --template .\SampleData\contract.tx
```

The sample writes the merged document to an output folder before submitting it to SignFabric. This makes it easy to inspect the generated document when debugging template data, merge fields, or signature field names.

### Conclusion

Combining TX Text Control mail merge with the SignFabric envelope API creates a clean integration path for document-driven business applications. Data can be merged into a reusable template inside your own application, and the resulting document can be handed directly to SignFabric as an envelope workflow.

The most important implementation detail is the mapping between API signer IDs and signature fields in the generated document. With that mapping in place, SignFabric can act as a signing service for generated documents from CRM, ERP, contract management, and document automation systems.

### Frequently Asked Questions

Can SignFabric envelopes be created from generated documents? 
--------------------------------------------------------------

Yes. A server-side application can generate or merge a document with TX Text Control and submit the resulting document to the SignFabric envelope API as a Base64 encoded file.

Which API endpoint creates a SignFabric envelope? 
--------------------------------------------------

The envelope integration API uses POST /api/v1/envelopes. The request includes the file name, Base64 encoded document, signer list, optional signing certificate ID, and whether the envelope should be sent immediately.

How does the console app authenticate against SignFabric? 
----------------------------------------------------------

The sample uses the local OAuth client-credentials endpoint at /api/v1/oauth/token. It requests a bearer token with scopes such as envelopes:create and envelopes:read, then sends that token with the envelope API request.

Why does SignFabric require txsign\_ signature field names? 
------------------------------------------------------------

SignFabric maps API signer IDs to physical signature fields in the document. A signer with the ID provider requires a signature field named txsign\_provider. This makes the recipient-to-field relationship explicit and easy to validate.

Can the generated document be inspected before it is sent? 
-----------------------------------------------------------

Yes. The sample writes the merged document to an output folder before submitting it to the API. This makes it easier to debug merge fields, generated content, and signature field names.

---

## About Bjoern Meyer

As CEO, Bjoern is the visionary behind our strategic direction and business development, bridging the gap between our customers and engineering teams. His deep passion for coding and web technologies drives the creation of innovative products. If you're at a tech conference, be sure to stop by our booth - you'll most likely meet Bjoern in person. With an advanced graduate degree (Dipl. Inf.) in Computer Science, specializing in AI, from the University of Bremen, Bjoern brings significant expertise to his role. In his spare time, Bjoern enjoys running, paragliding, mountain biking, and playing the piano.

- [LinkedIn](https://www.linkedin.com/in/bjoernmeyer/)
- [X](https://x.com/txbjoern)
- [GitHub](https://github.com/bjoerntx)

---

## Related Posts

- [Major SignFabric Updates: Stronger Audit Trails, Validation, and Recipient Workflows](https://www.textcontrol.com/blog/2026/06/17/major-signfabric-updates-stronger-audit-trails-validation-and-recipient-workflows/llms.txt)
- [Getting Started with SignFabric: From Clone to Your First Signature Envelope](https://www.textcontrol.com/blog/2026/06/02/getting-started-with-signfabric-from-clone-to-your-first-signature-envelope/llms.txt)
- [Use MailMerge in .NET on Linux to Generate Pixel-Perfect PDFs from DOCX Templates](https://www.textcontrol.com/blog/2025/05/27/use-mailmerge-in-dotnet-on-linux-to-generate-pixel-perfect-pdfs-from-docx-templates/llms.txt)
- [Generating Dynamic NDAs Using TX Text Control MailMerge in C# .NET](https://www.textcontrol.com/blog/2025/04/08/generating-dynamic-ndas-using-tx-text-control-mailmerge-in-csharp-dotnet/llms.txt)
- [Designing a Maintainable PDF Generation Web API in ASP.NET Core (Linux) C# with Clean Architecture and TX Text Control](https://www.textcontrol.com/blog/2025/03/27/designing-a-maintainable-pdf-generation-web-api-in-asp-net-core-linux-c-sharp-with-clean-architecture-and-tx-text-control/llms.txt)
- [Manipulating Table Cells During the MailMerge Process in .NET C#](https://www.textcontrol.com/blog/2024/12/03/manipulating-table-cells-during-the-mailmerge-process-in-net-csharp/llms.txt)
- [When to Generate Documents Server-Side Instead of Client-Side: A Focus on Data Security](https://www.textcontrol.com/blog/2024/10/04/when-to-generate-documents-server-side-instead-of-client-side-a-focus-on-data-security/llms.txt)
- [Mail Merge: Inserting Merge Blocks using the DataSourceManager in C#](https://www.textcontrol.com/blog/2024/10/02/mail-merge-inserting-merge-blocks-using-the-datasourcemanager-in-csharp/llms.txt)
- [Creating Advanced Tables in PDF and DOCX Documents with C#](https://www.textcontrol.com/blog/2024/09/30/creating-advanced-tables-in-pdf-and-docx-documents-with-csharp/llms.txt)
- [Designing the Perfect Contract Template for MailMerge in C#](https://www.textcontrol.com/blog/2024/09/26/designing-the-perfect-contract-template-for-mailmerge-in-csharp/llms.txt)
- [Video Tutorial: Creating a MailMerge Template and JSON Data Structure](https://www.textcontrol.com/blog/2024/08/16/video-tutorial-creating-a-mailmerge-template-and-json-data-structure/llms.txt)
- [Getting Started Video Tutorial: How to use the MailMerge and ServerTextControl Classes in ASP.NET Core C#](https://www.textcontrol.com/blog/2024/08/05/getting-started-video-tutorial-how-to-use-the-mailmerge-and-servertextcontrol-classes-in-asp-net-core-c/llms.txt)
- [Getting Started Videos: New Text Control YouTube Channel](https://www.textcontrol.com/blog/2024/08/02/getting-started-videos-new-text-control-youtube-channel/llms.txt)
- [Best Practices for Mail Merge and Form Field Processing in ASP.NET Core C# Applications](https://www.textcontrol.com/blog/2024/07/30/best-practices-for-mail-merge-and-form-field-processing-in-asp-net-core-csharp-applications/llms.txt)
- [Advantages of Flow Type Layout Reporting vs. Banded Reporting or PDF Template Engines in .NET C#](https://www.textcontrol.com/blog/2024/07/29/advantages-of-flow-type-layout-reporting-vs-banded-reporting-or-pdf-template-engines-in-net-c-sharp/llms.txt)
- [Designing a MailMerge Web API Endpoint with ASP.NET Core in C#](https://www.textcontrol.com/blog/2024/07/12/designing-a-mailmerge-web-api-endpoint-with-asp-net-core-in-c-sharp/llms.txt)
- [Enhancing Documents with QR Codes and Barcodes in .NET C#: A Comprehensive Guide](https://www.textcontrol.com/blog/2024/07/11/enhancing-documents-with-qr-codes-and-barcodes-in-net-csharp-a-comprehensive-guide/llms.txt)
- [Document Automation 101: Leveraging TX Text Control for Business Efficiency in .NET C# Applications](https://www.textcontrol.com/blog/2024/07/09/document-automation-101-leveraging-tx-text-control-for-business-efficiency-in-net-c-applications/llms.txt)
- [Merging Templates with MailMerge with Different Merge Field Settings in C#](https://www.textcontrol.com/blog/2023/12/16/merging-templates-with-mailmerge-with-different-merge-field-settings/llms.txt)
- [How to Mail Merge MS Word DOCX Documents in ASP.NET Core C#](https://www.textcontrol.com/blog/2023/10/16/how-to-mail-merge-ms-word-docx-documents-in-aspnet-core-csharp/llms.txt)
- [MailMerge: Working with Image Placeholders](https://www.textcontrol.com/blog/2022/12/22/mailmerge-working-with-image-placeholders/llms.txt)
- [Getting Started: ServerTextControl and MailMerge with ASP.NET Core](https://www.textcontrol.com/blog/2022/09/01/getting-started-servertextcontrol-and-mailmerge-with-aspnet-core/llms.txt)
- [Adding SVG Watermarks to Documents](https://www.textcontrol.com/blog/2022/01/28/adding-svg-watermarks-to-documents/llms.txt)
- [Using MailMerge in ASP.NET Core 6 Web Applications](https://www.textcontrol.com/blog/2022/01/27/using-mailmerge-in-aspnet-core-6-web-applications/llms.txt)
