//
// This code is part of Document Solutions for Word demos.
// Copyright (c) MESCIUS inc. All rights reserved.
//
using System;
using System.Globalization;
using GrapeCity.Documents.Word;
using GrapeCity.Documents.Word.Fields;
namespace DsWordWeb.Demos
{
// This sample shows how to use the STYLEREF field options to build a
// "running reference" that always displays the text of the nearest
// preceding paragraph formatted with a given style (e.g. the current
// chapter or section heading), similar to a running head in a printed
// book.
//
// LIMITATION: in DsWord 9.2.0 STYLEREF fields placed in a page header
// or footer are not resolved when exporting to PDF/image.
public class StyleRefFieldOpts
{
public GcWordDocument CreateDocx()
{
var doc = new GcWordDocument();
var h1 = doc.Styles[BuiltInStyleId.Heading1];
var h2 = doc.Styles[BuiltInStyleId.Heading2];
// A few chapters, each with a couple of subsections spread across
// multiple pages via filler text:
var rnd = Util.NewRandom();
for (int c = 1; c <= 3; c++)
{
doc.Body.AddParagraph($"Chapter {c}", h1);
for (int s = 1; s <= 2; s++)
{
doc.Body.AddParagraph($"Chapter {c}, Section {s}", h2);
for (int i = 0; i < rnd.Next(4, 6); i++)
{
doc.Body.AddParagraph(Util.LoremIpsumPar());
}
// A "breadcrumb" callout in the middle of the body text:
// both fields always resolve to the nearest preceding
// Heading1/Heading2 paragraph, so this line stays correct
// even if content is inserted or reordered above it.
var crumb = doc.Body.AddParagraph();
crumb.GetRange().Runs.Add("You are reading: ");
crumb.AddComplexField(new StyleRefFieldOptions(doc, h1.Name));
crumb.GetRange().Runs.Add(" → ");
crumb.AddComplexField(new StyleRefFieldOptions(doc, h2.Name));
}
}
// Update fields using a specific culture:
doc.UpdateFields(new GrapeCity.Documents.Word.Layout.WordLayoutSettings() { FontCollection = Util.FontCollection, Culture = CultureInfo.GetCultureInfo("en-US") });
// Done:
return doc;
}
}
}