Generate a PDF from a DOCX template in C#
This guide explains how to create a PDF document by merging data into a Word template.
Download samplePrepare the project
Register the SDK license before running SDK operations. For setup details, refer to the getting started with .NET SDK guide.
using GdPicture14;
LicenseManager license = new LicenseManager();license.RegisterKEY("");General principles
Word templating consists of the following elements:
- A DOCX file that will be used as the template.
- A template model that contains the placeholder values to replace in the DOCX template.
- Configuration for the template/model.
Template model
The template model can be an external JSON file or created programmatically. It must contain:
- A configuration containing a start and end delimiter.
- At least one placeholder-value pair. The placeholder name must correspond to the placeholder defined in the DOCX template.
Classes, methods, and properties
GdPictureOfficeTemplaterGdPictureOfficeTemplateConfigurationGdPictureOfficeTemplateDelimiterGdPictureOfficeTemplateBuilder
Populating a Word template
Nutrient .NET SDK (formerly GdPicture.NET) supports replacing placeholder text strings, loops, and dynamic tables. As the amount of content changes, the DOCX will automatically adjust and reflow across pages as needed. Plain-text replacements maintain the placeholder’s formatting from the DOCX template. For formatted HTML content, refer to HTML-valued placeholders.
The first step is to prepare the DOCX template with placeholders. This example uses {{ and }} as the delimiters to define the boundaries of placeholders.
Load the DOCX template:
GdPictureOfficeTemplater templater = new GdPictureOfficeTemplater();templater.LoadFromFile(@"input_template.docx");Now, prepare the data and configuration. For this example, use the following data model:
{ "config": { "delimiter": { "start": "{{", "end": "}}" } }, "model": { "name": "Alex Smith", "text": "Hello World!", "amount": "$249.99" }}The data model can be defined in a JSON file or loaded programmatically. The following snippet demonstrates how to define the model in a JSON file:
GdPictureStatus status = templater.SetTemplate(System.IO.File.ReadAllText("input_template_model.json"));The following snippet demonstrates how to define the model programmatically:
GdPictureOfficeTemplateConfiguration configuration = new GdPictureOfficeTemplateConfiguration(){ Delimiter = new GdPictureOfficeTemplateDelimiter { Start = "{{", End = "}}" }};
GdPictureOfficeTemplate template = GdPictureOfficeDefaultTemplateBuilder.CreateTemplate() .AddPlaceholderReplacement(placeholder: "name", replacementValue: "Petey Eff") .AddPlaceholderReplacement(placeholder: "text", replacementValue: "Hello World!") .AddPlaceholderReplacement(placeholder: "amount", replacementValue: "$420.69");
GdPictureStatus status = templater.SetTemplate(template, configuration);Next, replace the placeholders in the DOCX template with the data and save the result to a DOCX file:
GdPictureStatus status = templater.Process();
if (status == GdPictureStatus.OK){ status = templater.SaveToFile(@"result.docx");}The following image shows what the DOCX file looks like.
Lastly, convert the DOCX file into a PDF. The following example converts it to PDF/A using the PDF/A-1a PdfConformance level. However, you can choose whichever conformance enumeration you prefer.
using (GdPictureDocumentConverter oConverter = new GdPictureDocumentConverter()){ GdPictureStatus status = oConverter.LoadFromFile(@"result.docx", GdPicture14.DocumentFormat.DocumentFormatDOCX); if (status == GdPictureStatus.OK) { status = oConverter.SaveAsPDF("output.pdf", PdfConformance.PDF_A_1a); }}Complete runnable example
The following runnable example populates the Word template with JSON data, saves the populated DOCX file, and converts it to PDF:
GdPictureOfficeTemplater templater = new GdPictureOfficeTemplater();GdPictureStatus status = templater.LoadFromFile(@"input_template.docx");if (status != GdPictureStatus.OK){ throw new Exception(status.ToString());}
status = templater.SetTemplate(System.IO.File.ReadAllText("input_template_model.json"));if (status != GdPictureStatus.OK){ throw new Exception(status.ToString());}
status = templater.Process();if (status != GdPictureStatus.OK){ throw new Exception(status.ToString());}
status = templater.SaveToFile(@"result.docx");if (status != GdPictureStatus.OK){ throw new Exception(status.ToString());}
using GdPictureDocumentConverter converter = new GdPictureDocumentConverter();status = converter.LoadFromFile(@"result.docx", GdPicture14.DocumentFormat.DocumentFormatDOCX);if (status != GdPictureStatus.OK){ throw new Exception(status.ToString());}
status = converter.SaveAsPDF("output.pdf", PdfConformance.PDF_A_1a);if (status != GdPictureStatus.OK){ throw new Exception(status.ToString());}Alternative: Converting template output to PDF/UA
If your workflow requires accessibility compliance, you can convert the processed DOCX template output to PDF/UA:
GdPictureOfficeTemplater templater = new GdPictureOfficeTemplater();templater.SetTemplate(System.IO.File.ReadAllText("input_template_model.json"));
templater.LoadFromFile(@"input_template.docx");templater.Process();templater.SaveToFile(@"output.docx");
using GdPictureDocumentConverter converter = new GdPictureDocumentConverter();converter.LoadFromFile(@"output.docx");converter.SaveAsPDF(@"output.pdf", PdfConformance.PDF_UA_1);Using HTML-valued placeholders
Starting with version 14.4.11.1, Word templates support HTML-valued placeholders. Use them to insert formatted text, lists, links, tables, and base64-embedded images instead of literal HTML tags.
Set the placeholder’s model value to an object with "_type": "html" and an html property containing the markup. A plain string remains literal text, even when it contains HTML tags.
To adapt the earlier example, place {{text}} in its own paragraph in the Word template and save the following model as input_template_model.json:
{ "config": { "delimiter": { "start": "{{", "end": "}}" } }, "model": { "name": "Alex Smith", "text": { "_type": "html", "html": "<p><b>Equipment</b></p><ul><li>Engine</li><li>Service plan</li></ul>" }, "amount": "$249.99" }}Use the same SetTemplate, LoadFromFile, Process, and save steps shown above. The generated Word document contains a bold “Equipment” paragraph followed by a bulleted list. Convert that document to PDF with the existing conversion workflow.
Formatting and placement
The placeholder’s formatting is the starting point for HTML content. HTML formatting adds to or overrides it. For example, font-weight: normal clears bold formatting inherited from the placeholder.
Inline HTML stays within the placeholder’s paragraph. Block elements, such as paragraphs, lists, and tables, split the paragraph at the placeholder. Surrounding text stays before or after the inserted blocks in separate paragraphs.
When a loop opens and closes within the same paragraph in a table cell, use {{tr#items}}{{description}}{{/items}} to repeat the whole row. In the dynamic table loop example, the opening and closing markers are in different cells of the same row, so row repetition is inferred without tr#. Both rules apply to HTML and plain-text values.
Supported content and limitations
- Word output supports formatted text, headings, lists, links, and tables. Link targets support
http,https, andmailtoschemes. - Images use base64
data:URIs in the HTML. Supported formats are PNG, JPEG, GIF, BMP, and TIFF. Other image sources aren’t fetched; their alternative text is used instead. - Use inline
styleattributes for supported formatting. CSS classes and<style>elements don’t apply styles, and<script>elements are discarded. - HTML values longer than 1,048,576 characters are inserted as literal text.
Using loops
To create a loop, add an array of objects to the data model. For every object within the array, the loop’s body is replicated during each cycle of the loop when the DOCX and data model are processed. Here’s an example of such a JSON file:
{ "config": { "delimiter": { "start": "{{", "end": "}}" } }, "model": { "loop1": [ { "loopDesc1": "Monday", "loopDesc2": "Tuesday" }, { "loopDesc1": "Wednesday", "loopDesc2": "Thursday" }, { "loopDesc1": "Friday", "loopDesc2": "Saturday" } ], "loop2": [ { "loopDesc": "Red" }, { "loopDesc": "Orange" }, { "loopDesc": "Green" } ] }}The following is an example of such a DOCX template.

For bulleted or numbered lists, the opening placeholder must immediately precede the start of the list, and the closing placeholder must immediately follow the end of the list.
Combining the JSON with the DOCX produces the following output.

For an example of combining loops with tables, refer to the dynamic table loop example below.
Using conditionals
Conditionals enable a template to dynamically insert and format data based on conditions defined within the template itself. Conditionals can be combined with loops for more complex dynamic documents.
The template syntax for implementing conditionals is straightforward. It uses special markers to denote the beginning and end of a conditional block, as well as to indicate the condition being tested:
#condition— Marks the beginning of a block that should be rendered if the condition istrue.^condition— Marks the beginning of a block that should be rendered if the condition isfalse(theelsepart)./condition— Marks the end of a conditional block.
Here’s a simple example showing this syntax for an isBlue condition:
{{#isBlue}}Blue{{/isBlue}}{{^isBlue}}Red{{/isBlue}}{ "config": { "delimiter": { "start": "{{", "end": "}}" } }, "model": { "isBlue": true }}Here’s a more complex example with conditionals.

You can combine the template above with the following JSON file:
{ "config": { "delimiter": { "start": "{{", "end": "}}" } }, "model": { "isConsulting": false, "consultingField": "N/A", "scopeExhibit": "Exhibit A", "startDate": "March 1, 2024", "endDate": "February 28, 2025", "autoRenew": true }}In this case, the output will be the following DOCX, which can then be converted to PDF.

Dynamic table loop example
This example shows three different approaches to using loops for dynamically inserting rows into a table. You can download the DOCX template used in this example.

Option 1 — Using a model loaded from a JSON file
In this first approach, you’ll populate the DOCX template with data from a JSON file. You can download the JSON file used in this example:
using (GdPictureOfficeTemplater templater = new GdPictureOfficeTemplater()){ GdPictureStatus status = templater.SetTemplate(System.IO.File.ReadAllText("table.json"));
if (status == GdPictureStatus.OK) { status = templater.LoadFromFile("table.docx");
if (status == GdPictureStatus.OK) { status = templater.Process();
if (status == GdPictureStatus.OK) { // Replace placeholders with actual values. status = templater.SaveToFile("result.docx");
if (status == GdPictureStatus.OK) { // Create PDF document. using (GdPictureDocumentConverter oConverter = new GdPictureDocumentConverter()) { status = oConverter.LoadFromFile("result.docx", GdPicture14.DocumentFormat.DocumentFormatDOCX);
if (status == GdPictureStatus.OK) { status = oConverter.SaveAsPDF("output.pdf", PdfConformance.PDF_A_1a); } } } } } }}Option 2 — Creating a model programmatically
In this second approach, you’ll populate the DOCX template by programmatically creating the model.
First, create the template model:
static GdPictureOfficeTemplate CreateTemplate(){ return GdPictureOfficeDefaultTemplateBuilder.CreateTemplate() .AddSection<GdPictureOfficeTemplate>(sectionName: "products", product1 => { product1 .AddPlaceholderReplacement("product_name", "T-shirt (white)") .AddPlaceholderReplacement("qty", "1") .AddPlaceholderReplacement("cost", "$48.00"); }, product2 => { product2 .AddPlaceholderReplacement("product_name", "Pants") .AddPlaceholderReplacement("qty", "1") .AddPlaceholderReplacement("cost", "$85.00"); }, product3 => { product3 .AddPlaceholderReplacement("product_name", "Leather Jacket (red)") .AddPlaceholderReplacement("qty", "1") .AddPlaceholderReplacement("cost", "$478.00"); }, product4 => { product4 .AddPlaceholderReplacement("product_name", "Fedora") .AddPlaceholderReplacement("qty", "1") .AddPlaceholderReplacement("cost", "$79.00"); }, product5 => { product5 .AddPlaceholderReplacement("product_name", "Glove") .AddPlaceholderReplacement("qty", "1") .AddPlaceholderReplacement("cost", "$34.00"); }) .AddPlaceholderReplacement(placeholder: "subtotal", replacementValue: "$724.00") .AddPlaceholderReplacement(placeholder: "tax", replacementValue: "$72.40") .AddPlaceholderReplacement(placeholder: "total", replacementValue: "$796.40");}Next, set the configuration for the model:
static GdPictureOfficeTemplateConfiguration GetConfiguration(){ return new GdPictureOfficeTemplateConfiguration() { Delimiter = new GdPictureOfficeTemplateDelimiter { Start = "{{", End = "}}" } };}Now, process the file, replacing the placeholders with actual values and creating a PDF:
using (GdPictureOfficeTemplater templater = new GdPictureOfficeTemplater()){ GdPictureStatus status = templater.SetTemplate(CreateTemplate(), GetConfiguration());
if (status == GdPictureStatus.OK) { status = templater.LoadFromFile("table.docx");
if (status == GdPictureStatus.OK) { // Replace placeholders with actual values. status = templater.Process();
if (status == GdPictureStatus.OK) { status = templater.SaveToFile("result.docx");
if (status == GdPictureStatus.OK) { // Create PDF document. using (GdPictureDocumentConverter oConverter = new GdPictureDocumentConverter()) { status = oConverter.LoadFromFile("result.docx", GdPicture14.DocumentFormat.DocumentFormatDOCX);
if (status == GdPictureStatus.OK) { status = oConverter.SaveAsPDF("output.pdf", PdfConformance.PDF_A_1a); } } } } } }}Option 3 — Creating a model programmatically using a custom builder
In this third approach, you’ll use a custom builder to populate the DOCX template.
First, create the custom builder:
class TableIntelligentLoopTemplate : GdPictureOfficeTemplateBuilder<TableIntelligentLoopTemplate>{ public TableIntelligentLoopTemplate AddProductName(string value) { return AddPlaceholderReplacement("product_name", value); }
public TableIntelligentLoopTemplate AddQty(string value) { return AddPlaceholderReplacement("qty", value); }
public TableIntelligentLoopTemplate AddCost(string value) { return AddPlaceholderReplacement("cost", value); }}Next, create the template/model using the custom builder:
static GdPictureOfficeTemplate CreateTemplateUsingCustomBuilder(){ return GdPictureOfficeDefaultTemplateBuilder.CreateTemplate() .AddSection<TableIntelligentLoopTemplate>(sectionName: "products", product1 => { product1 .AddProductName("T-shirt (white)") .AddQty("1") .AddCost("$48.00"); }, product2 => { product2 .AddProductName("Pants") .AddQty("1") .AddCost("$85.00"); }, product3 => { product3 .AddProductName("Leather Jacket (red)") .AddQty("1") .AddCost("$478.00"); }, product4 => { product4 .AddProductName("Fedora") .AddQty("1") .AddCost("$79.00"); }, product5 => { product5 .AddProductName("Glove") .AddQty("1") .AddCost("$34.00"); }) .AddPlaceholderReplacement(placeholder: "subtotal", replacementValue: "$724.00") .AddPlaceholderReplacement(placeholder: "tax", replacementValue: "$72.40") .AddPlaceholderReplacement(placeholder: "total", replacementValue: "$796.40");}Set the configuration for the model:
static GdPictureOfficeTemplateConfiguration GetConfiguration(){ return new GdPictureOfficeTemplateConfiguration() { Delimiter = new GdPictureOfficeTemplateDelimiter { Start = "{{", End = "}}" } };}Now, process the file, replacing the placeholders with actual values and creating a PDF:
using (GdPictureOfficeTemplater templater = new GdPictureOfficeTemplater()){ GdPictureStatus status = templater.SetTemplate(CreateTemplateUsingCustomBuilder(), GetConfiguration());
if (status == GdPictureStatus.OK) { status = templater.LoadFromFile("table.docx");
if (status == GdPictureStatus.OK) { // Replace placeholders with actual values. status = templater.Process();
if (status == GdPictureStatus.OK) { status = templater.SaveToFile("result.docx");
if (status == GdPictureStatus.OK) { // Create PDF document. using (GdPictureDocumentConverter oConverter = new GdPictureDocumentConverter()) { status = oConverter.LoadFromFile("result.docx", GdPicture14.DocumentFormat.DocumentFormatDOCX);
if (status == GdPictureStatus.OK) { status = oConverter.SaveAsPDF("output.pdf", PdfConformance.PDF_A_1a); } } } } } }}Automatic reflow example
Text reflow refers to the automatic adjustment of text within a document or display area to ensure it fits within the given space without overflowing or leaving excessive empty space. This process involves moving words and characters to new lines, pages, or columns as needed based on the available width and height of the display area, the font size, and other formatting settings.

Here’s the JSON you’ll use:
{ "config": { "delimiter": { "start": "{{", "end": "}}" } }, "model": { "clauses": [ { "clause": "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." }, { "clause": "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." }, { "clause": "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." }, { "clause": "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." }, { "clause": "Lorem ipsum dolor sit amet, consectetur adipiscing elit..." } ], "title": "Purchase and Sale Agreement" }}The example below shows how to generate a PDF from a DOCX template where the content is reflowed into another column by using a data model loaded from a JSON file. For an example of how to create the model programmatically, refer to the dynamic table loop example above:
using (GdPictureOfficeTemplater templater = new GdPictureOfficeTemplater()){ GdPictureStatus status = templater.SetTemplate(System.IO.File.ReadAllText("model.json"));
if (status == GdPictureStatus.OK) { status = templater.LoadFromFile("template.docx");
if (status == GdPictureStatus.OK) { status = templater.Process();
if (status == GdPictureStatus.OK) { // Replace placeholders with actual values. status = templater.SaveToFile("result.docx");
if (status == GdPictureStatus.OK) { // Create PDF document. using (GdPictureDocumentConverter oConverter = new GdPictureDocumentConverter()) { status = oConverter.LoadFromFile("result.docx", GdPicture14.DocumentFormat.DocumentFormatDOCX);
if (status == GdPictureStatus.OK) { status = oConverter.SaveAsPDF("output.pdf", PdfConformance.PDF_A_1a); } } } } } }}