# Programmatically Fill, Flatten, and Export DOCX Form Templates to PDF in C# .NET

> Learn how to fill, flatten and export DOCX form templates to PDF programmatically in C# .NET. This article provides a step-by-step guide on how to use the TX Text Control library to achieve this, along with code examples and best practice recommendations for working with DOCX templates and PDF exports.

- **Author:** Bjoern Meyer
- **Published:** 2026-04-10
- **Modified:** 2026-04-10
- **Description:** Learn how to fill, flatten and export DOCX form templates to PDF programmatically in C# .NET. This article provides a step-by-step guide on how to use the TX Text Control library to achieve this, along with code examples and best practice recommendations for working with DOCX templates and PDF exports.
- **10 min read** (1989 words)
- **Tags:**
  - ASP.NET
  - PDF
  - DOCX
  - Forms
- **Web URL:** https://www.textcontrol.com/blog/2026/04/10/programmatically-fill-flatten-and-export-docx-form-templates-to-pdf-in-csharp-dotnet/
- **LLMs URL:** https://www.textcontrol.com/blog/2026/04/10/programmatically-fill-flatten-and-export-docx-form-templates-to-pdf-in-csharp-dotnet/llms.txt
- **LLMs-Full URL:** https://www.textcontrol.com/blog/2026/04/10/programmatically-fill-flatten-and-export-docx-form-templates-to-pdf-in-csharp-dotnet/llms-full.txt

---

Documents are rarely created from scratch. Instead, they are based on Microsoft Word templates that contain predefined form fields. These templates can be automatically filled with application data and exported as finalized PDF documents.

Typical workflows include:

- Generating contracts or agreements from templates
- Populating HR documents with employee data
- Creating invoices or application forms
- Converting completed templates into non-editable PDF documents
 
A common workflow looks like this:

- Start with a DOCX template containing form fields
- Use MailMerge to populate the fields with application data
- Either:
- **pre-select** the form fields so users can still edit the document, or
- **replace** the form fields with actual content to flatten the document
 
- Export the result to PDF
 
![Workflow diagram](https://s1-www.textcontrol.com/assets/dist/blog/2026/04/10/a/assets/workflow.webp "Workflow diagram")

TX Text Control supports this workflow through the MailMerge class and its FormFieldMergeType property, which controls how form fields are handled during the merge process. The documented options include Preselect, which pre-populates form fields where possible, and Replace, which replaces the form fields with merged content.

### Installing the Required NuGet Package

To implement this workflow in a .NET application, install the **TXTextControl.TextControl.Core.SDK** package. In your environment, this package is available either from the [Text Control private NuGet feed](https://www.textcontrol.com/blog/2026/02/09/text-control-private-nuget-feed/llms-full.txt) or from the offline package source created during setup installation.

> **Learn more**
> 
> The Text Control private NuGet feed lets developers install licensed TX Text Control .NET packages with automatic license injection. Authentication uses API tokens tied to assigned serials. The feed integrates with Visual Studio and CI/CD pipelines on GitHub, GitLab, and Azure DevOps.
> 
> [Text Control Private NuGet Feed](https://www.textcontrol.com/blog/2026/02/09/text-control-private-nuget-feed/llms-full.txt)

Using the NuGet Package Manager Console:

 ```powershell
Install-Package TXTextControl.TextControl.Core.SDK
```

After installing the package, you can use TXTextControl.ServerTextControl class to load the DOCX template and MailMerge to merge business data into the contained form fields.

### Why is MailMerge Important Here?

The key feature of this workflow is that the form fields are not filled in manually, one by one. Instead, they are merged automatically using the MailMerge engine. As the referenced Text Control article explains, the MailMerge class merges object or JSON data with form fields, and the merge behavior is controlled by FormFieldMergeType.

This is especially useful when your template contains:

- Many form fields that need to be filled
- Complex templates with conditional content
- Dynamic data sources that can change frequently
 
By using MailMerge, you can automate the process of filling out the form fields based on your application's data, which saves time and reduces the risk of errors compared to manual filling.

### Scenario 1: Pre-Select Form Fields

In the first scenario, the template is populated with known values, but the form should still be editable. This is useful when you want to help a user by pre-filling out a document, but still allow them to review or complete it later. In this case, set the FormFieldMergeType to Preselect. This will populate the form fields with the provided data; however, the fields will remain active and editable in the resulting document.

 ```
using TXTextControl;
using TXTextControl.DocumentServer;

public class ContractData
{
    public string customer_name { get; set; }
    public string company_name { get; set; }
    public DateTime contract_date { get; set; }
    public bool approved { get; set; }
    public string contract_type { get; set; }
}

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    // Load the DOCX template with form fields
    tx.Load("template.docx", StreamType.WordprocessingML);

    ContractData data = new ContractData()
    {
        customer_name = "John Doe",
        company_name = "Example Corporation",
        contract_date = DateTime.Today,
        approved = true,
        contract_type = "Standard"
    };

    using (MailMerge mm = new MailMerge())
    {
        mm.TextComponent = tx;

        // Pre-populate the form fields, but keep them editable
        mm.FormFieldMergeType = FormFieldMergeType.Preselect;
        mm.MergeObject(data);
    }

    // Export as editable PDF form
    tx.Save("preselected-form.pdf", StreamType.AdobePDF);
}
```

This approach is ideal when the generated PDF should behave like a form. The original article uses this exact pattern: load the template, set the FormFieldMergeType to Preselect, merge the object, and save the result as a PDF. The resulting PDF will have the form fields pre-filled but still editable, allowing users to make changes if needed.

### Scenario 2: Replace Form Fields to Flatten the Document

In the second scenario, the result should not be an editable form anymore. Instead, the merged values should become fixed document content. This is the flattening step.

The article describes flattening as replacing the form field with the selected form field value and removing the form field itself. It also demonstrates how to use FormFieldMergeType.Replace to replace form fields with database content during the merge process.

 ```
using TXTextControl;
using TXTextControl.DocumentServer;

public class ContractData
{
    public string customer_name { get; set; }
    public string company_name { get; set; }
    public DateTime contract_date { get; set; }
    public bool approved { get; set; }
    public string contract_type { get; set; }
}

using (ServerTextControl tx = new ServerTextControl())
{
    tx.Create();

    // Load the DOCX template with form fields
    tx.Load("template.docx", StreamType.WordprocessingML);

    ContractData data = new ContractData()
    {
        customer_name = "John Doe",
        company_name = "Example Corporation",
        contract_date = DateTime.Today,
        approved = true,
        contract_type = "Standard"
    };

    using (MailMerge mm = new MailMerge())
    {
        mm.TextComponent = tx;

        // Replace form fields with actual content
        // This effectively flattens the template content
        mm.FormFieldMergeType = FormFieldMergeType.Replace;
        mm.MergeObject(data);
    }

    // Export the flattened result to PDF
    tx.Save("flattened-contract.pdf", StreamType.AdobePDF);
}
```

This is the more important workflow when the final document is intended for:

- Archiving or record-keeping
- Sharing with external parties
- Ensuring the content cannot be modified after generation
 
Since the form fields are replaced during the merge process, the resulting PDF is a finalized document with the merged content as static text, not an editable form. This is ideal for contracts, agreements, and any other document where it is important that the content remain unchanged after generation.

### Pre-Select vs Replace: Which One to Use?

Both approaches have their uses, and your choice should depend on your application's specific requirements and the intended use of the generated PDF. The practical difference is straightforward:

 | Preselect | Replace |
|---|---|
| Form fields are filled with known values but remain editable. | Form fields are replaced with merged content, resulting in a flattened document. |
| Ideal for documents that may require further editing or review. | Ideal for finalized documents that should not be modified after generation. |

 

So if your workflow is:

DOCX with form fields → fill out → flatten → export to PDF

then FormFieldMergeType.Replace is the most direct and clean MailMerge-based implementation.

### Filling Form Fields Programmatically

If you want to programmatically fill out the form fields without using MailMerge, you can do so by iterating through the form fields in the document and setting their values directly. While this approach gives you more control over the process, it requires more code to handle each field individually.

After loading the template, the form fields can be populated with application data.

 ```
foreach (FormField field in tx.FormFields)
{
    if (field.Name == "customer_name")
        field.Text = "John Doe";

    if (field.Name == "customer_company")
        field.Text = "Example Corporation";

    if (field.Name == "contract_date")
        field.Text = DateTime.Today.ToShortDateString();
}
```

#### Flattening the Form Fields Programmatically

To flatten the document programmatically, you can iterate through the form fields and replace them with their values. The Remove method of the FormFieldCollection can be used to replace the field with the actual content. The following function will iterate through all of the fields in the form in order to remove the field functionality.

 ```
private void FlattenFormFields(ServerTextControl textControl) {
  int fieldCount = textControl.FormFields.Count;

  for (int i = 0; i < fieldCount; i++) {
    TextFieldCollectionBase.TextFieldEnumerator fieldEnum =
      textControl.FormFields.GetEnumerator();
    fieldEnum.MoveNext();

    FormField curField = (FormField)fieldEnum.Current;
    textControl.FormFields.Remove(curField, true);
  }
}
```

### Conclusion

When generating documents from Word templates in .NET, MailMerge provides a clean way to handle form fields programmatically.

Use FormFieldMergeType.Preselect when you want to create a PDF form that is already filled but still editable. Use FormFieldMergeType.Replace when you want to flatten the template by replacing all form fields with their merged values before exporting to PDF. This distinction, and the sample workflow around it, is documented in the referenced Text Control article.

TX Text Control is a great choice for automating document generation in .NET applications thanks to its powerful features for working with DOCX templates and exporting to PDF.

### Frequently Asked Questions

How can I generate PDFs from Word templates in .NET? 
-----------------------------------------------------

You can generate PDFs from Microsoft Word (DOCX) templates by loading the template into a document processing engine, filling its form fields with application data, and exporting the result as a PDF. With TX Text Control, this workflow can be automated using the ServerTextControl class to load the template and the MailMerge class to merge business data into the form fields before exporting the document to PDF.

How do I convert a Word template to PDF in C#? 
-----------------------------------------------

To convert a Word template to PDF in C#, load the DOCX template using ServerTextControl, populate the template fields using MailMerge or by setting form field values programmatically, and then export the document using the Save method with StreamType.AdobePDF. This allows applications to generate PDFs directly from Word-based templates.

What is the difference between Preselect and Replace in MailMerge? 
-------------------------------------------------------------------

The FormFieldMergeType property of the MailMerge class controls how form fields are handled during the merge process. Using Preselect fills the form fields with values but keeps them editable in the resulting document. Using Replace inserts the values and removes the form field itself, effectively flattening the document so the merged content becomes static text.

How can I flatten form fields when generating a PDF in .NET? 
-------------------------------------------------------------

Flattening form fields means converting interactive fields into static document content. In TX Text Control, this can be achieved during MailMerge by setting FormFieldMergeType.Replace, which replaces the form field with the merged value. Alternatively, you can iterate through the FormFields collection and remove them programmatically after inserting their values.

When should I flatten form fields before exporting to PDF? 
-----------------------------------------------------------

Flattening form fields is useful when the generated document should no longer be editable. This is typically required for contracts, agreements, invoices, or archived documents. By replacing the form fields with their merged values, the final PDF contains fixed content that cannot be modified through form controls.

How do I install TX Text Control for document processing in .NET? 
------------------------------------------------------------------

The required package can be installed using the NuGet Package Manager Console. Install the **TXTextControl.TextControl.Core.SDK** package using the following command:

```powershell
Install-Package TXTextControl.TextControl.Core.SDK
```

The package is available through the Text Control private NuGet feed or through the offline package source that is created when installing the TX Text Control setup.

Can MailMerge merge data from objects or JSON sources? 
-------------------------------------------------------

Yes. The MailMerge class supports merging data from .NET objects, JSON data, and other structured sources. This makes it easy to populate Word templates with data retrieved from databases, APIs, CRM systems, or other application services.

Is it possible to fill Word form fields without using MailMerge? 
-----------------------------------------------------------------

Yes. Form fields can also be filled programmatically by iterating through the FormFields collection and setting the values directly. However, MailMerge is typically the preferred approach when working with many fields or structured data sources because it reduces code complexity and simplifies template-based document generation.

Why use Word templates for document generation in .NET applications? 
---------------------------------------------------------------------

Word templates allow business users to design and update document layouts without modifying application code. Developers can then populate the templates with data using MailMerge. This separation of layout design and application logic makes document generation workflows easier to maintain and scale.

Can TX Text Control generate both editable and finalized PDF documents? 
------------------------------------------------------------------------

Yes. By controlling the MailMerge behavior, developers can decide whether the resulting document remains editable or becomes a finalized document. Using FormFieldMergeType.Preselect keeps form fields editable, while FormFieldMergeType.Replace flattens the form fields so the exported PDF contains static content.

---

## 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

- [Create Fillable PDFs from HTML Forms in C# ASP.NET Core Using a WYSIWYG Template](https://www.textcontrol.com/blog/2026/03/17/create-fillable-pdfs-from-html-forms-in-csharp-aspnet-core-using-a-wysiwyg-template/llms.txt)
- [Designing the Perfect PDF Form with TX Text Control in .NET C#](https://www.textcontrol.com/blog/2025/12/16/designing-the-perfect-pdf-form-with-tx-text-control-in-dotnet-csharp/llms.txt)
- [PDF Conversion in .NET: Convert DOCX, HTML and more with C#](https://www.textcontrol.com/blog/2025/08/05/pdf-conversion-in-dotnet-convert-docx-html-and-more-with-csharp/llms.txt)
- [Streamline Data Collection with Embedded Forms in C# .NET](https://www.textcontrol.com/blog/2025/08/02/streamline-data-collection-with-embedded-forms-in-csharp-dotnet/llms.txt)
- [Convert MS Word DOCX to PDF including Text Reflow using .NET C# on Linux](https://www.textcontrol.com/blog/2025/06/10/convert-ms-word-docx-to-pdf-including-text-reflow-using-dotnet-csharp-on-linux/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)
- [Convert MS Word DOCX to PDF with Form Fields in C# .NET: Preserve or Flatten Form Fields](https://www.textcontrol.com/blog/2025/02/26/convert-ms-word-docx-to-pdf-with-form-fields-in-csharp-dotnet/llms.txt)
- [Export and Import Adobe PDF XFDF XML Files in .NET C#](https://www.textcontrol.com/blog/2025/01/22/export-and-import-adobe-pdf-xfdf-xml-files-in-net-c-sharp/llms.txt)
- [Sign Documents with a Self-Signed Digital ID From Adobe Acrobat Reader in .NET C#](https://www.textcontrol.com/blog/2024/08/12/sign-documents-with-a-self-signed-digital-id-from-adobe-acrobat-reader-in-net-c-sharp/llms.txt)
- [Generating MS Word DOCX and PDF Documents with ASP.NET Core C#](https://www.textcontrol.com/blog/2024/04/05/generating-ms-word-docx-and-pdf-documents-with-asp-net-core-c-sharp/llms.txt)
- [How to Load and View PDF Documents in ASP.NET Core C#](https://www.textcontrol.com/blog/2023/10/20/how-to-load-and-view-pdf-documents-in-aspnet-core-csharp/llms.txt)
- [How to Create and Deploy PDF Forms in ASP.NET Core C#](https://www.textcontrol.com/blog/2023/10/17/how-to-create-and-deploy-pdf-forms-in-aspnet-core-csharp/llms.txt)
- [Converting MS Word DOCX Documents to PDF in C#](https://www.textcontrol.com/blog/2023/10/16/converting-ms-word-docx-documents-to-pdf-in-csharp/llms.txt)
- [Generating Interactive PDF Forms by Injecting JavaScript](https://www.textcontrol.com/blog/2022/03/31/generating-interactive-pdf-forms-by-injecting-javascript/llms.txt)
- [Creation of Custom Electronic Signature Boxes](https://www.textcontrol.com/blog/2021/06/15/creation-of-custom-electronic-signature-boxes/llms.txt)
- [Don't Print Your Documents! Streamlined Document Processes in Your Applications](https://www.textcontrol.com/blog/2021/06/09/dont-print-your-documents/llms.txt)
- [Creating PDF Documents from MS Word DOCX in C#](https://www.textcontrol.com/blog/2021/02/26/creating-pdf-documents-from-ms-word-docx-in-csharp/llms.txt)
- [Why Structured E-Invoices Still Need Tamper Protection using C# and .NET](https://www.textcontrol.com/blog/2026/03/24/why-structured-e-invoices-still-need-tamper-protection-using-csharp-and-dotnet/llms.txt)
- [Why HTML to PDF Conversion is Often the Wrong Choice for Business Documents in C# .NET](https://www.textcontrol.com/blog/2026/03/13/why-html-to-pdf-conversion-is-often-the-wrong-choice-for-business-documents-in-csharp-dot-net/llms.txt)
- [A Complete Guide to Converting Markdown to PDF in .NET C#](https://www.textcontrol.com/blog/2026/01/07/a-complete-guide-to-converting-markdown-to-pdf-in-dotnet-csharp/llms.txt)
- [Why PDF Creation Belongs at the End of the Business Process](https://www.textcontrol.com/blog/2026/01/02/why-pdf-creation-belongs-at-the-end-of-the-business-process/llms.txt)
- [How to Extend the Default Style Mapping when Converting DOCX to Markdown in .NET C#](https://www.textcontrol.com/blog/2025/12/22/how-to-extend-the-default-style-mapping-when-converting-docx-to-markdown-in-dotnet-csharp/llms.txt)
- [Why Defining MIME Types for PDF/A Attachments Is Essential](https://www.textcontrol.com/blog/2025/12/10/why-defining-mime-types-for-pdfa-attachments-is-essential/llms.txt)
- [Validate Digital Signatures and the Integrity of PDF Documents in C# .NET](https://www.textcontrol.com/blog/2025/11/14/validate-digital-signatures-and-the-integrity-of-pdf-documents-in-csharp-dotnet/llms.txt)
- [Validate PDF/UA Documents and Verify Electronic Signatures in C# .NET](https://www.textcontrol.com/blog/2025/11/13/validate-pdf-ua-documents-and-verify-electronic-signatures-in-csharp-dotnet/llms.txt)
