SubSuperScript.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 System.Text.RegularExpressions;
using GrapeCity.Documents.Word;

namespace DsWordWeb.Demos
{
    // This sample shows how to render subscript and superscript text.
    public class SubSuperScript
    {
        public GcWordDocument CreateDocx()
        {
            var doc = new GcWordDocument();
            var sec = doc.Body.Sections.First;
            var para = sec.GetRange().Paragraphs.Add();

            // Get a random 'lorem ipsum' paragraph:
            var text = Util.LoremIpsum(1, 18, 20, 20, 20)[0];

            // Split the paragraph into 'lorem', 'ipsum' and everything else:
            const string sub = "lorem";
            const string super = "ipsum";
            var frags = Regex.Split(text, $"({sub})|({super})");

            // Create subscript and superscript styles:
            var sSub = doc.Styles.Add("My Subscript", StyleType.Character);
            sSub.Font.VerticalPosition = VerticalTextPosition.Subscript;
            var sSup = doc.Styles.Add("My Superscript", StyleType.Character);
            sSup.Font.VerticalPosition = VerticalTextPosition.Superscript;

            // Add text to a TextLayout using special formats for 'lorem' and 'ipsum':
            foreach (var frag in frags)
            {
                if (frag == sub)
                    para.GetRange().Runs.Add(frag, sSub);
                else if (frag == super)
                    para.GetRange().Runs.Add(frag, sSup);
                else
                    para.GetRange().Runs.Add(frag);
            }

            // Done:
            return doc;
        }
    }
}