Generates docx document from docx template using data in JSON-format. This is a port from novodocx with some improvements.
- Install
CUSTIS.Generator.Docx
package - Prepare docx-template (see instructions below)
- Populate template with your data:
var jsonData = "{'someData': 'hello'}"; // data to populate template with
var templateFile = "template.docx"; // file with template
// populate file with data
var docProcessor = new WordDocumentProcessor(NullLogger<WordDocumentProcessor>.Instance);
using var filled = await docProcessor.PopulateDocumentTemplate(templateFile, jsonData);
// save file
await using var resultFileStream = new FileStream("destination.docx", FileMode.OpenOrCreate, FileAccess.Write);
await filled.CopyToAsync(resultFileStream);
Open Developer Tab in MS Word and enter Design Mode (instructions).
- Use
Plain Text Content Control
if you need to render text without line breaks - Open
Properties
- Fill
Tag
with the field name from JSON
Data sample:
var jsonData = @"{'name': 'CUSTIS.Generator.Docx'}";
Output: Hello, CUSTIS.Generator.Docx!
- Use
Rich Text Content Control
if you need to render HTML - Open
Properties
- Fill
Tag
with the field name from JSON
Limitations: only <p>
, <br>
, <ol>
, <ul>
, <li>
tags are processed. All other tags are skipped.
Data sample:
var jsonData = @"{'formatted': 'Hello,<br/>CUSTIS.<red>Generator</red>.Docx!'}";
Output:
Hello,
CUSTIS.Generator.Docx!
- Use
Repeated Section Control
if you need to render array - Open
Properties
- Fill
Tag
with the name of array from JSON - Use either
Plain
orRich Text Content Controls
insideRepeated Section Control
to render text
Arrays can be rendered as paragraphs, lists or even tables. You can render nested arrays too (with any number of nested lists).
Data sample:
var jsonData = @"{'sports': [{'name': 'swimming'}, {'name': 'football'}]}";
Output:
Sports:
1. Name: swimming
2. Name: football
You can manage visibility of content using conditional expressions.
- Wrap the content into
Plain
orRich Text Content Control
- Open
Properties
- Fill
Tag
withvisible: expression
(e.g.visible: myField == 'git'
)
You can use other content controls inside visibility control.
Supported expressions:
operand
,!operand
;op1 == op2
,op1 != op2
;- only for ints:
op1 < op2
,op1 > op2
,op1 <= op2
,op1 >= op2
.
Examples of expressions with their result (including !null
, null == null
, etc.) could be found in ExpressionEvaluatorTests.
Json Path expressions can be used to query data (use it as Tag
in Word content control). CUSTIS.Generator.Docx
uses Json.NET
(from Newtonsoft). You can get some samples of JSON path here.
MS Word doesn't allow to repeat columns. The workaround is to create multiple tables (with 1, 2, ... columns) and to wrap each table in visibility expression.
- Change version in
Directory.Build.props
- Use internal CUSTIS git to push to nuget