Create Word documents using C# templates

This guide explains how to use the Nutrient Document Converter Services (DCS) API to fill a Word .docx template with data provided through a JSON model. This is especially useful for generating contracts, invoices, reports, or any document requiring templated content.

Prerequisites

  • A .docx template file with placeholders such as {{name}} and {{invoicenumber}}.
  • A JSON model defining placeholder-value mappings.
  • DCS installed and running.
  • Implemented OpenService() and CloseService() methods from DocumentConverterServiceClient sample code.

Template placeholders

A template model is a JSON format structure. It can be either an external JSON file or created programmatically. It includes a configuration section (containing the delimiter characters) and a model section containing at least one placeholder-value pair.

Sample model

{
"config": {
"delimiter": {
"start": "{{",
"end": "}}"
}
},
"model": {
"name": "Jules Winnfield",
"invoicenumber": "90121",
"paymentdue": "28/09/2020",
"grandtotal": "81.00",
"yourname": "Johan Schmidt",
"yourposition": "Finance department",
"yourcontactdetails": "Systems testing"
}
}

Sample Word template

Word template showing placeholders for name, invoice number, payment due date, and contact information

Sample code

/// <summary>
/// Create new Word documents by filling in Word template files.
/// </summary>
/// <param name="ServiceURL">URL endpoint for the Document Converter Services.</param>
/// <param name="templateFile">Word document template file.</param>
/// <param name="dataFile">JSON format model file.</param>
/// <param name="targetFolder">Target folder to receive the output file.</param>
static void TestTemplate(string ServiceURL, string templateFile, string dataFile, string targetFolder)
{
// Read the template file as a byte array.
byte[] sourceBytes = File.ReadAllBytes(templateFile);
// Read the JSON data.
string dataValues = File.ReadAllText(dataFile);
DocumentConverterServiceClient client = null;
// Simple `OpenOptions` object.
OpenOptions openOptions = new OpenOptions();
openOptions.FileExtension = Path.GetExtension(dataFile);
openOptions.OriginalFileName = Path.GetFileName(dataFile);
try
{
// Open a client.
client = OpenService(ServiceURL);
// Call the `FillWordTemplate` method on DCS.
BatchResult result = client.FillWordTemplate(sourceBytes, openOptions, dataValues);
// Check that a result is returned.
if (result != null)
{
// Create the output folder if it doesn’t exist.
if (!Directory.Exists(targetFolder))
{
Directory.CreateDirectory(targetFolder);
}
// Get the filename from the result.
string filename = result.FileName;
Console.WriteLine($"File {Path.GetFullPath(Path.Combine(targetFolder, filename))} created");
// Write the result to the target filename.
File.WriteAllBytes(Path.Combine(targetFolder, filename), result.File);
}
else
{
Console.WriteLine($"No result returned");
}
}
catch (Exception ex)
{
Console.WriteLine($"{ex.Message}");
}
finally
{
if (client != null)
{
// Close the service.
CloseService(client);
}
}
}

The code creates a new Word document by filling the template with the JSON data. The output file is saved to the specified target folder with the filename returned by DCS, maintaining the original .docx format.

Troubleshooting

Connection error: Cannot connect to DCS service

  • Ensure DCS is running and accessible
  • Verify the service URL in your code matches your DCS installation
  • Check that no firewall is blocking the connection

Template processing error: Invalid placeholders

  • Verify that placeholders in your Word template match the JSON model keys exactly
  • Ensure placeholder delimiters in the JSON config match those used in the template
  • Check that the Word template file is accessible and not corrupted

JSON data error: Invalid JSON format

  • Validate your JSON file syntax using an online JSON validator
  • Ensure all string values are correctly quoted
  • Check for trailing commas or missing brackets

File access error: Permission denied

  • Verify that the application has read access to the template and JSON files
  • Check that the output directory has write permissions
  • Ensure files aren’t locked by other applications

What’s next

Now that you can create Word documents from templates, explore these related DCS capabilities with C#: