ComplexFields.cs
//
// This code is part of Document Solutions for Word demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using GrapeCity.Documents.Word;

namespace DsWordWeb.Demos
{
    // This sample demonstrates the use of complex fields.
    // It adds a complex field that tests whether the current date
    // is the New Year day, and modifies the text in the document
    // accordingly. See also DateAndTime sample.
    public class ComplexFields
    {
        public GcWordDocument CreateDocx()
        {
            GcWordDocument doc = new GcWordDocument();

            // Add a title:
            doc.Body.Paragraphs.Add("Testing whether it is the New Year yet").Style = doc.Styles[BuiltInStyleId.Title];

            // Add a paragraph and get its range:
            var rng = doc.Body.Paragraphs.Add().GetRange();
            // Add a static text:
            rng.Runs.Add("Today is ");

            // Add a complex field with "IF" instruction. We also provide 
            // a pre-calculated value for the sake of PDF export, as DsWord
            // does not yet support field calculation - see DateAndTime.
            // Note also that because the code field will not be calculated
            // in the PDF export, the "NOT " won't be bold in it:
            var val = Util.TimeNow().DayOfYear == 1 ? "" : "NOT ";
            var f = rng.ComplexFields.Add("IF ", val);
            // Add a complex field with "DATE" instruction:
            f.GetCodeRange().ComplexFields.Add(" DATE \\@ \"M-d\" ");
            // Add additional instruction to the "IF" field to compare the nested
            // DATE field result with "1-1" and return "NOT " if it is true,
            // also make the "NOT " bold if visible: 
            f.CodeFields.Add("<> \"1-1\" \"NOT \"").ParentRun.Font.Bold = true;

            // Add a static text:
            rng.Runs.Add("New Year's Day.");

            // Done:
            return doc;
        }
    }
}