Filling/creating Word documents using Word 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() helpers.

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

sample-word-template

Sample code

/// <summary>
        /// Create new Word documents by filling in Word template files.
        /// </summary>
        /// <param name="ServiceURL">URL endpoint for the PDF Converter service.</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 does not 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);
                }
            }
        }