This article demonstrates how to add page numbering, table of content and footnote to Word document by using fields in C#.
Introduction
With the rapid development of information technology, MS has introduced the concept of Field, which makes the process more flexible and convenient by automation. What is indeed the word fields? They are blocks of codes that guides Word on inserting texts, pictures, pages or other information. This article will focus on how to implement some of the common field applications programmatically using the excellent Word API in C#.
- Page Numbering and Repaginating
- The TOC and Index
- Footnote and Cross Reference
The Specific Implementations of the Field Applications
A.Page Numbering and Repaginating
In fact, word document is flow layout orientated and it is inaccessible to obtain the information of its lines and pages. However, in order to have a better visual effect, MS designed the virtual concept of page, which provides a great convenience for reading and locating. Spire.Doc also makes it easy to achieve page numbering and repaginating.
//Firstly, load a sample document and get the first section
Document doc = new Document("Summary_of_Science.docx");
Section section = doc.Sections[0];
//Move to the footer
var footer = section.HeadersFooters.Footer;
//To have a better visual effect, I create a table in the footer to display the page number
var table = footer.AddTable(false);
table.ResetCells(1, 2);
//Add a section break so as to repaginate (e.g. at the location of paragraph 15)
Paragraph para = section.Paragraphs[14];
para.InsertSectionBreak(SectionBreakType.NoBreak);
//Add a paragraph into the first cell and insert the current date
Paragraph DateParagraph = table.Rows[0].Cells[0].AddParagraph();
DateParagraph.AppendField("time", FieldType.FieldDate);
//Align the date to the left of the cell
DateParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Left;
//Add a paragraph into the second cell and insert the page number
Paragraph pageParagraph = table.Rows[0].Cells[1].AddParagraph();
pageParagraph.AppendText("Page ");
pageParagraph.AppendField("page number", FieldType.FieldPage);
pageParagraph.AppendText(" of ");
pageParagraph.AppendField("number of pages", FieldType.FieldSectionPages);
pageParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right;

Figure 1. Page Numbering
//Repaginate in the second section
doc.Sections[1].PageSetup.RestartPageNumbering = true;
//Move to the footer and add a paragraph to set page number
footer = doc.Sections[1].HeadersFooters.Footer;
Paragraph pageParagraph2 = footer.AddParagraph();
pageParagraph2.AppendText("Page ");
pageParagraph2.AppendField("page number", FieldType.FieldPage);
//Save to file
doc.SaveToFile("PageAndDateField.docx");
Figure 2. Repaginating
B.The TOC and Index
TOC, abbreviated from Table of Contents, is a list of multiple levels of headings in the document. For those large documents, TOC is certainly an indispensable part since people are able to consult the outline and page index as well as take a quick jump. The TOC and index can be reached effortlessly by using the code segment below. Kindly note there are two ways to implement TOC in the following example.
Occasion 1. Insert table of contents directly in an existing document with heading styles by using AppendTOC method
//Load a document with hierarchical headings
Document doc = new Document();
doc.LoadFromFile("toc.docx");
//Create a paragraph and insert it at the head of the document
Paragraph para = new Paragraph(doc);
doc.Sections[0].Paragraphs.Insert(0, para);
//Append the related TOC to this paragraph
para.AppendTOC(1, 3);
//Update the Toc field to display the result
doc.UpdateTableOfContents();
doc.SaveToFile("AppendToc.docx", FileFormat.Docx);
Figure 3. Append Toc
Occasion 2. Create a new document from scratch and build table of contents programmatically with specified format in field codes
//Create a new document and add a section
Document doc1 = new Document();
Section section = doc1.AddSection();
//Add some paragraphs with hierarchical headings
Paragraph Hpara1 = section.AddParagraph();
Hpara1.AppendText("Heading1");
Hpara1.ApplyStyle(BuiltinStyle.Heading1);
Paragraph Hpara2 = section.AddParagraph();
Hpara2.AppendText("Heading2");
Hpara2.ApplyStyle(BuiltinStyle.Heading2);
Paragraph Hpara3 = section.AddParagraph();
Hpara3.AppendText("Heading3");
Hpara3.ApplyStyle(BuiltinStyle.Heading3);
//Initialize a new instance of “TableOfContent” with specified switches
TableOfContent toc = new TableOfContent(doc1, "{\\o \"1-3\" \\h \\z \\u}");
//Create a new paragraph and insert it in the front
Paragraph para1 = section.AddParagraph();
doc1.Sections[0].Paragraphs.Insert(0, para1);
//Add the toc object into the paragraph
para1.Items.Add(toc);
//Append a field separator mark. This process cannot be omitted.
para1.AppendFieldMark(FieldMarkType.FieldSeparator);
para1.AppendText("TOC");
//Append a field end mark. This process cannot be omitted.
para1.AppendFieldMark(FieldMarkType.FieldEnd);
//Set the created Toc object as the document's Toc
doc1.TOC = toc;
//Update the Toc field to display the result
doc1.UpdateTableOfContents();
doc1.SaveToFile("ProgramaticToc.docx",FileFormat.Docx);

Figure 4. Programmatic TOC
C.Footnote and Cross Reference
Footnote is a series of annotations attached at the bottom of the page to show explanation of certain terms in the document. The form of the annotation can be diverse, including picture, text, table, chart, etc. When people want to reference the same footnote at different places, the cross reference is needed. With Spire.Doc, reaching the goal is just a piece of cake.
Step 1. Create a footnote
//Load a document
Document document = new Document();
document.LoadFromFile("Summary_of_Science.docx");
//Find the text where the footnote will be added
TextSelection ts = document.FindString("Kepler's laws", true, true);
//Get the text range that the text belongs to
TextRange textrRange= ts.GetAsOneRange();
//Get the paragraph that the text range lies in
Paragraph paragraph = textrRange.OwnerParagraph;
//Create a footnote and design its content and format
Footnote footnote = new Footnote(document);
footnote.FootnoteType = FootnoteType.Footnote;
footnote.TextBody.AddParagraph().AppendText("Kepler's laws of planetary motion are three scientific laws describing the motion of planets around the Sun");
footnote.MarkerCharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
//Insert the footnote at the specific location, that is, after the text “Kepler’s laws”
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(textrRange) + 1, footnote);
Step 2. Create a cross-reference field and link it to the footnote. This process can be summarized as below. 1. Create a bookmark to wrap up the footnote. 2. Create a cross-reference field and link it to the footnote through the bookmark. 3. Locate the text you want to reference the same footnote and insert the cross-reference field, pay attention to add the field separator mark and the field end mark.
//Create new bookmark with footnote mark
BookmarkStart start = new BookmarkStart(document, "_FootNote1");
BookmarkEnd end = new BookmarkEnd(document, "_FootNote1");
//Insert bookmark identifier around the footnote
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(footnote), start);
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(footnote) + 1, end);
//Add a cross-reference field, and link it to footnote through the bookmark name
Field field = new Field(document);
field.Type = FieldType.FieldNoteRef;
field.Code = @" NOTEREF _FootNote1 \f \h \* MERGEFORMAT ";
//Locate the text range where you want to reference the same footnote
textrRange = document.FindString("planetary motion law", true, true).GetAsOneRange();
//Get the paragraph the text range lies in
paragraph = textrRange.OwnerParagraph;
//Insert the cross-reference field just after the position of the text range in the paragraph
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(textrRange) + 1, field);
//Create a field mark object to mark the separator of the field and insert it after the cross-reference field. This process cannot be omitted.
FieldMark fieldmark = new FieldMark(document, FieldMarkType.FieldSeparator);
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(textrRange) + 2, fieldmark);
//Create a new text range and set its SubSuperScript style
TextRange tr = new TextRange(document);
tr.Text = "2";
tr.CharacterFormat.SubSuperScript = SubSuperScript.SuperScript;
paragraph.ChildObjects.Insert(paragraph.ChildObjects.IndexOf(textrRange) + 3, tr)
//Create a field end mark and insert it after all the manipulation on the cross-reference field. This process cannot be omitted.
FieldMark fieldEnd = new FieldMark(document, FieldMarkType.FieldEnd);
paragraph.ChildObjects.Add(fieldEnd);
//Save the docuemnt
document.SaveToFile("sameFootNote10101.docx", FileFormat.Docx);

Figure 5. FoteNote and CrossReference
Conclusion
This article has demonstrated how to get approach to the popular word field applications programmatically with a powerful Word API. Any comment is greatly appreciated.