ComplexFields.cs
//
// This code is part of GrapeCity Documents for Word samples.
// Copyright (c) GrapeCity, Inc. All rights reserved.
//
using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using GrapeCity.Documents.Word;

namespace GcWordWeb.Samples
{
    // This sample demonstrates the use of complext 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();
            var sec = doc.Body.Sections.First;

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

            // Add a paragraph and get its range:
            var rng = sec.GetRange().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 GcWord
            // 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 = DateTime.Now.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;
        }
    }
}