How to apply a Word DOCX Template in C# .NET Framework
2 min readJul 20, 2020
Applying DOCX templates is a difficult task at the best of times, made still more painful when setting it up within .NET Framework. You wouldn’t believe the pitfalls that exist to drag you down into the depths of frustration. However, I have a nice, tidy solution that can get you through it, and do so in just a matter of minutes of simple setup. Let’s begin.
First we grab our package from NuGet:
Install-Package Cloudmersive.APIClient.NET.DocumentAndDataConvert -Version 3.2.8
Then, look at the below example for implementing it into your code:
using System;using System.Diagnostics;using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Api;using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Client;using Cloudmersive.APIClient.NET.DocumentAndDataConvert.Model;namespace Example{public class ConvertTemplateApplyDocxTemplateExample{public void main(){// Configure API key authorization: ApikeyConfiguration.Default.AddApiKey("Apikey", "YOUR_API_KEY");// Uncomment below to setup prefix (e.g. Bearer) for API key, if needed// Configuration.Default.AddApiKeyPrefix("Apikey", "Bearer");var apiInstance = new ConvertTemplateApi();var inputFile = new System.IO.Stream(); // System.IO.Stream | Input file to perform the operation on.var templateDefinition = new Object(); // Object | Template definition for the document, including what values to replace (optional)try{// Apply Word DOCX templatebyte[] result = apiInstance.ConvertTemplateApplyDocxTemplate(inputFile, templateDefinition);Debug.WriteLine(result);}catch (Exception e){Debug.Print("Exception when calling ConvertTemplateApi.ConvertTemplateApplyDocxTemplate: " + e.Message );}}}}
And you’re done! Simple as that.