C#: Create a Table Of Contents for a Newly Created Word Document
Creating a table of contents in a newly created Word document is an important means to enhance document quality, improve reading experience, and effectively convey information. As a navigational guide for the document, the table of contents provides readers with a way to quickly locate and navigate through the document's content. Through the table of contents, readers can swiftly grasp the document's structure and content organization, saving reading time and boosting work efficiency. This article will explain how to use Spire.Doc for .NET to create a table of contents for a newly created Word document within a C# project.
- C# Create a Table Of Contents Using Heading Styles
- C# Create a Table Of Contents Using Outline Level Styles
- C# Create a Table Of Contents Using Image Captions
- C# Create a Table Of Contents Using Table Captions
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
C# Create a Table Of Contents Using Heading Styles
Using heading styles to create a table of contents is a method to automatically generate a table of contents in a Word document by identifying title and subtitles in the document using different levels of heading styles. Here are the detailed steps:
- Create a Document object.
- Add a section using the Document.AddSection() method.
- Add a paragraph using the Section.AddParagraph() method.
- Create a table of contents object using the Paragraph.AppendTOC(int lowerLevel, int upperLevel) method.
- Create a CharacterFormat object and set the font.
- Apply a heading style to the paragraph using the Paragraph.ApplyStyle(BuiltinStyle.Heading1) method.
- Add text content using the Paragraph.AppendText() method.
- Apply character formatting to the text using the TextRange.ApplyCharacterFormat() method.
- Update the table of contents using the Document.UpdateTableOfContents() method.
- Save the document using the Document.SaveToFile() method.
- C#
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Formatting; namespace SpireDocDemo { internal class Program { static void Main(string[] args) { // Create a new document object Document doc = new Document(); // Add a section to the document Section section = doc.AddSection(); // Add a paragraph Paragraph TOCparagraph = section.AddParagraph(); TOCparagraph.AppendTOC(1, 3); // Create a CharacterFormat object and set the font CharacterFormat characterFormat1 = new CharacterFormat(doc); characterFormat1.FontName = "Microsoft YaHei"; // Create another CharacterFormat object CharacterFormat characterFormat2 = new CharacterFormat(doc); characterFormat2.FontName = "Microsoft YaHei"; characterFormat2.FontSize = 12; // Add a paragraph with Heading 1 style Paragraph paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(BuiltinStyle.Heading1); // Add text and apply character formatting TextRange textRange1 = paragraph.AppendText("Overview"); textRange1.ApplyCharacterFormat(characterFormat1); // Add regular content paragraph = section.Body.AddParagraph(); TextRange textRange2 = paragraph.AppendText("Spire.Doc for .NET is a professional Word .NET library specifically designed for developers to create, read, write, convert, compare and print Word documents on any .NET platform (Target .NET Framework, .NET Core, .NET Standard, .NET 5.0, .NET 6.0, Xamarin & Mono Android) with fast and high quality performance."); textRange2.ApplyCharacterFormat(characterFormat2); // Add a paragraph with Heading 1 style paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(BuiltinStyle.Heading1); textRange1 = paragraph.AppendText("Main Functions"); textRange1.ApplyCharacterFormat(characterFormat1); // Add a paragraph with Heading 2 style paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(BuiltinStyle.Heading2); textRange1 = paragraph.AppendText("Only Spire.Doc, No Microsoft Office Automation"); textRange1.ApplyCharacterFormat(characterFormat1); // Add regular content paragraph = section.Body.AddParagraph(); textRange2 = paragraph.AppendText("Spire.Doc for .NET is a totally independent .NET Word class library which doesn't require Microsoft Office installed on system. Microsoft Office Automation is proved to be unstable, slow and not scalable to produce MS Word documents. Spire.Doc for .NET is many times faster than Microsoft Word Automation and with much better stability and scalability."); textRange2.ApplyCharacterFormat(characterFormat2); // Add a paragraph with Heading 3 style paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(BuiltinStyle.Heading3); textRange1 = paragraph.AppendText("Word Versions"); textRange1.ApplyCharacterFormat(characterFormat1); paragraph = section.Body.AddParagraph(); textRange2 = paragraph.AppendText("Word97-03 Word2007 Word2010 Word2013 Word2016 Word2019"); textRange2.ApplyCharacterFormat(characterFormat2); // Add a paragraph with Heading 2 style paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(BuiltinStyle.Heading2); textRange1 = paragraph.AppendText("Convert File Documents with High Quality"); textRange1.ApplyCharacterFormat(characterFormat1); // Add regular content paragraph = section.Body.AddParagraph(); textRange2 = paragraph.AppendText("By using Spire.Doc for .NET, users can save Word Doc/Docx to stream, save as web response and convert Word Doc/Docx to XML, Markdown, RTF, EMF, TXT, XPS, EPUB, HTML, SVG, ODT and vice versa. Spire.Doc for .NET also supports to convert Word Doc/Docx to PDF and HTML to image."); textRange2.ApplyCharacterFormat(characterFormat2); // Add a paragraph with Heading 2 style paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(BuiltinStyle.Heading2); textRange1 = paragraph.AppendText("Other Technical Features"); textRange1.ApplyCharacterFormat(characterFormat1); // Add regular content paragraph = section.Body.AddParagraph(); textRange2 = paragraph.AppendText("By using Spire.Doc, developers can build any type of a 32-bit or 64-bit .NET application including ASP.NET, Web Services, WinForms, Xamarin and Mono Android, to create and handle Word documents."); textRange2.ApplyCharacterFormat(characterFormat2); // Update the table of contents doc.UpdateTableOfContents(); // Save the document doc.SaveToFile("CreateTOCUsingHeadingStyles.docx", FileFormat.Docx2016); // Release resources doc.Dispose(); } } }
C# Create a Table Of Contents Using Outline Level Styles
In a Word document, a table of contents can also be created using outline level styles. The ParagraphFormat.OutlineLevel property can be used to specify the level style of a paragraph in the outline. Subsequently, these outline level styles can be applied to the table of contents creation rules through the TableOfContent.SetTOCLevelStyle() method. Here are the detailed steps:
- Create a Document object.
- Add a section using the Document.AddSection() method.
- Create a ParagraphStyle object and set the outline level using ParagraphStyle.ParagraphFormat.OutlineLevel = OutlineLevel.Level1.
- Add the created ParagraphStyle object to the document using the Document.Styles.Add() method.
- Add a paragraph using the Section.AddParagraph() method.
- Create a table of contents object using the Paragraph.AppendTOC(int lowerLevel, int upperLevel) method.
- Set the default setting for creating the table of contents with heading styles to False, TableOfContent.UseHeadingStyles = false.
- Apply the outline level style to the table of contents rules using the TableOfContent.SetTOCLevelStyle(int levelNumber, string styleName) method.
- Create a CharacterFormat object and set the font.
- Apply the style to the paragraph using the Paragraph.ApplyStyle(ParagraphStyle.Name) method.
- Add text content using the Paragraph.AppendText() method.
- Apply character formatting to the text using the TextRange.ApplyCharacterFormat() method.
- Update the table of contents using the Document.UpdateTableOfContents() method.
- Save the document using the Document.SaveToFile() method.
- C#
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Formatting; namespace SpireDocDemo { internal class Program { static void Main(string[] args) { // Create a document object Document doc = new Document(); Section section = doc.AddSection(); // Define Outline Level 1 ParagraphStyle titleStyle1 = new ParagraphStyle(doc); titleStyle1.Name = "T1S"; titleStyle1.ParagraphFormat.OutlineLevel = OutlineLevel.Level1; titleStyle1.CharacterFormat.Bold = true; titleStyle1.CharacterFormat.FontName = "Microsoft YaHei"; titleStyle1.CharacterFormat.FontSize = 18f; titleStyle1.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left; doc.Styles.Add(titleStyle1); // Define Outline Level 2 ParagraphStyle titleStyle2 = new ParagraphStyle(doc); titleStyle2.Name = "T2S"; titleStyle2.ParagraphFormat.OutlineLevel = OutlineLevel.Level2; titleStyle2.CharacterFormat.Bold = true; titleStyle2.CharacterFormat.FontName = "Microsoft YaHei"; titleStyle2.CharacterFormat.FontSize = 16f; titleStyle2.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left; doc.Styles.Add(titleStyle2); // Define Outline Level 3 ParagraphStyle titleStyle3 = new ParagraphStyle(doc); titleStyle3.Name = "T3S"; titleStyle3.ParagraphFormat.OutlineLevel = OutlineLevel.Level3; titleStyle3.CharacterFormat.Bold = true; titleStyle3.CharacterFormat.FontName = "Microsoft YaHei"; titleStyle3.CharacterFormat.FontSize = 14f; titleStyle3.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Left; doc.Styles.Add(titleStyle3); // Add a paragraph Paragraph TOCparagraph = section.AddParagraph(); TableOfContent toc = TOCparagraph.AppendTOC(1, 3); toc.UseHeadingStyles = false; toc.UseHyperlinks = true; toc.UseTableEntryFields = false; toc.RightAlignPageNumbers = true; toc.SetTOCLevelStyle(1, titleStyle1.Name); toc.SetTOCLevelStyle(2, titleStyle2.Name); toc.SetTOCLevelStyle(3, titleStyle3.Name); // Define character format CharacterFormat characterFormat = new CharacterFormat(doc); characterFormat.FontName = "Microsoft YaHei"; characterFormat.FontSize = 12; // Add a paragraph and apply outline level style 1 Paragraph paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(titleStyle1.Name); paragraph.AppendText("Overview"); // Add a paragraph and set the text content paragraph = section.Body.AddParagraph(); TextRange textRange = paragraph.AppendText("Spire.Doc for .NET is a professional Word .NET library specifically designed for developers to create, read, write, convert, compare and print Word documents on any .NET platform (Target .NET Framework, .NET Core, .NET Standard, .NET 5.0, .NET 6.0, Xamarin & Mono Android) with fast and high quality performance."); textRange.ApplyCharacterFormat(characterFormat); // Add a paragraph and apply outline level style 1 paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(titleStyle1.Name); paragraph.AppendText("Main Functions"); // Add a paragraph and apply outline level style 2 paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(titleStyle2.Name); paragraph.AppendText("Only Spire.Doc, No Microsoft Office Automation"); // Add a paragraph and set the text content paragraph = section.Body.AddParagraph(); textRange = paragraph.AppendText("Spire.Doc for .NET is a totally independent .NET Word class library which doesn't require Microsoft Office installed on system. Microsoft Office Automation is proved to be unstable, slow and not scalable to produce MS Word documents. Spire.Doc for .NET is many times faster than Microsoft Word Automation and with much better stability and scalability."); textRange.ApplyCharacterFormat(characterFormat); // Add a paragraph and apply outline level style 3 paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(titleStyle3.Name); paragraph.AppendText("Word Versions"); // Add a paragraph and set the text content paragraph = section.Body.AddParagraph(); textRange = paragraph.AppendText("Word97-03 Word2007 Word2010 Word2013 Word2016 Word2019"); textRange.ApplyCharacterFormat(characterFormat); // Add a paragraph and apply outline level style 2 paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(titleStyle2.Name); paragraph.AppendText("Convert File Documents with High Quality"); // Add a paragraph and set the text content paragraph = section.Body.AddParagraph(); textRange = paragraph.AppendText("By using Spire.Doc for .NET, users can save Word Doc/Docx to stream, save as web response and convert Word Doc/Docx to XML, Markdown, RTF, EMF, TXT, XPS, EPUB, HTML, SVG, ODT and vice versa. Spire.Doc for .NET also supports to convert Word Doc/Docx to PDF and HTML to image."); textRange.ApplyCharacterFormat(characterFormat); // Add a paragraph and apply outline level style 2 paragraph = section.Body.AddParagraph(); paragraph.ApplyStyle(titleStyle2.Name); paragraph.AppendText("Other Technical Features"); // Add a paragraph and set the text content paragraph = section.Body.AddParagraph(); textRange = paragraph.AppendText("By using Spire.Doc, developers can build any type of a 32-bit or 64-bit .NET application including ASP.NET, Web Services, WinForms, Xamarin and Mono Android, to create and handle Word documents."); textRange.ApplyCharacterFormat(characterFormat); // Update the table of contents doc.UpdateTableOfContents(); // Save the document doc.SaveToFile("CreateTOCUsingOutlineStyles.docx", FileFormat.Docx2016); // Release resources doc.Dispose(); } } }
C# Create a Table Of Contents Using Image Captions
Using the Spire.Doc library, you can create a table of contents based on image captions with the TableOfContent tocForImage = new TableOfContent(Document, " \\h \\z \\c \"Image\"") method. Here are the detailed steps:
- Create a Document object.
- Add a section using the Document.AddSection() method.
- Create a table of content object with TableOfContent tocForImage = new TableOfContent(Document, " \\h \\z \\c \"Image\"") and specify the style of the table of contents.
- Add a paragraph using the Section.AddParagraph() method.
- Add the table of content object to the paragraph using the Paragraph.Items.Add(tocForImage) method.
- Add a field separator using the Paragraph.AppendFieldMark(FieldMarkType.FieldSeparator) method.
- Add the text content "TOC" using the Paragraph.AppendText("TOC") method.
- Add a field end mark using the Paragraph.AppendFieldMark(FieldMarkType.FieldEnd) method.
- Add an image using the Paragraph.AppendPicture() method.
- Add a caption paragraph for the image using the DocPicture.AddCaption() method, including product information and formatting.
- Update the table of contents to reflect changes in the document using the Document.UpdateTableOfContents(tocForImage) method.
- Save the document using the Document.SaveToFile() method.
- C#
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Formatting; namespace SpireDocDemo { internal class Program { static void Main(string[] args) { // Create a document object Document doc = new Document(); // Add a section to the document Section section = doc.AddSection(); // Create a table of content object for images TableOfContent tocForImage = new TableOfContent(doc, " \\h \\z \\c \"Picture\""); // Add a paragraph to the section Paragraph tocParagraph = section.Body.AddParagraph(); // Add the TOC object to the paragraph tocParagraph.Items.Add(tocForImage); // Add a field separator tocParagraph.AppendFieldMark(FieldMarkType.FieldSeparator); // Add text content tocParagraph.AppendText("TOC"); // Add a field end mark tocParagraph.AppendFieldMark(FieldMarkType.FieldEnd); // Add a blank paragraph to the section section.Body.AddParagraph(); // Add a paragraph to the section Paragraph paragraph = section.Body.AddParagraph(); // Add an image DocPicture docPicture = paragraph.AppendPicture("images/Doc-NET.png"); docPicture.Width = 100; docPicture.Height = 100; // Add a caption paragraph for the image Paragraph pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph; pictureCaptionParagraph.AppendText(" Spire.Doc for .NET product"); pictureCaptionParagraph.Format.AfterSpacing = 20; // Continue adding paragraphs to the section paragraph = section.Body.AddParagraph(); docPicture = paragraph.AppendPicture("images/PDF-NET.png"); docPicture.Width = 100; docPicture.Height = 100; pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph; pictureCaptionParagraph.AppendText(" Spire.PDF for .NET product"); pictureCaptionParagraph.Format.AfterSpacing = 20; paragraph = section.Body.AddParagraph(); docPicture = paragraph.AppendPicture("images/XLS-NET.png"); docPicture.Width = 100; docPicture.Height = 100; pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph; pictureCaptionParagraph.AppendText(" Spire.XLS for .NET product"); pictureCaptionParagraph.Format.AfterSpacing = 20; paragraph = section.Body.AddParagraph(); docPicture = paragraph.AppendPicture("images/PPT-NET.png"); docPicture.Width = 100; docPicture.Height = 100; pictureCaptionParagraph = docPicture.AddCaption("Picture", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph; pictureCaptionParagraph.AppendText(" Spire.Presentation for .NET product"); // Update the table of contents doc.UpdateTableOfContents(tocForImage); // Save the document to a file doc.SaveToFile("CreateTOCWithImageCaptions.docx", Spire.Doc.FileFormat.Docx2016); // Dispose of the document object doc.Dispose(); } } }
C# Create a Table Of Contents Using Table Captions
You can also create a table of contents using table captions by using the method TableOfContent tocForTable = new TableOfContent(Document, " \\h \\z \\c \"Table\""). Here are the detailed steps:
- Create a Document object.
- Add a section using the Document.AddSection() method.
- Create a table of content object TableOfContent tocForTable = new TableOfContent(Document, " \\h \\z \\c \"Table\"") and specify the style of the table of contents.
- Add a paragraph using the Section.AddParagraph() method.
- Add the table of content object to the paragraph using the Paragraph.Items.Add(tocForTable) method.
- Add a field separator using the Paragraph.AppendFieldMark(FieldMarkType.FieldSeparator) method.
- Add the text content "TOC" using the Paragraph.AppendText("TOC") method.
- Add a field end mark using the Paragraph.AppendFieldMark(FieldMarkType.FieldEnd) method.
- Add a table using the Section.AddTable() method and set the number of rows and columns using the Table.ResetCells(int rowsNum, int columnsNum) method.
- Add a table caption paragraph using the Table.AddCaption() method, including product information and formatting.
- Update the table of contents to reflect changes in the document using the Document.UpdateTableOfContents(tocForTable) method.
- Save the document using the Document.SaveToFile() method.
- C#
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Formatting; namespace SpireDocDemo { internal class Program { static void Main(string[] args) { // Create a new document Document doc = new Document(); // Add a section to the document Section section = doc.AddSection(); // Create a TableOfContent object TableOfContent tocForTable = new TableOfContent(doc, " \\h \\z \\c \"Table\""); // Add a paragraph in the section to place the TableOfContent object Paragraph tocParagraph = section.Body.AddParagraph(); tocParagraph.Items.Add(tocForTable); tocParagraph.AppendFieldMark(FieldMarkType.FieldSeparator); tocParagraph.AppendText("TOC"); tocParagraph.AppendFieldMark(FieldMarkType.FieldEnd); // Add two empty paragraphs in the section section.Body.AddParagraph(); section.Body.AddParagraph(); // Add a table in the section Table table = section.Body.AddTable(true); table.ResetCells(1, 3); // Add a caption paragraph for the table Paragraph tableCaptionParagraph = table.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph; tableCaptionParagraph.AppendText(" One row three columns"); tableCaptionParagraph.Format.AfterSpacing = 18; // Add a new table in the section table = section.Body.AddTable(true); table.ResetCells(3, 3); // Add a caption paragraph for the second table tableCaptionParagraph = table.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph; tableCaptionParagraph.AppendText(" Three rows three columns"); tableCaptionParagraph.Format.AfterSpacing = 18; // Add another new table in the section table = section.Body.AddTable(true); table.ResetCells(5, 3); // Add a caption paragraph for the third table tableCaptionParagraph = table.AddCaption("Table", CaptionNumberingFormat.Number, CaptionPosition.BelowItem) as Paragraph; tableCaptionParagraph.AppendText(" Five rows three columns"); // Update the table of contents doc.UpdateTableOfContents(tocForTable); // Save the document to a specified file doc.SaveToFile("CreateTOCUsingTableCaptions.docx", Spire.Doc.FileFormat.Docx2016); // Dispose resources doc.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Create a Cross-Reference to Bookmark in Word in C#, VB.NET
A cross-reference refers to related information elsewhere in the same document. You can create cross-references to any existing items such as headings, footnotes, bookmarks, captions, and numbered paragraphs. This article will show you how to create a cross-reference to bookmark using Spire.Doc with C# and VB.NET.
Step 1: Create a Document instance.
Document doc = new Document(); Section section = doc.AddSection();
Step 2: Insert a bookmark.
Paragraph paragraph = section.AddParagraph(); paragraph.AppendBookmarkStart("MyBookmark"); paragraph.AppendText("Text inside a bookmark"); paragraph.AppendBookmarkEnd("MyBookmark");
Step 3: Create a cross-reference field, and link it to the bookmark through bookmark name.
Field field = new Field(doc); field.Type = FieldType.FieldRef; field.Code = @"REF MyBookmark \p \h";
Step 4: Add a paragraph, and insert the field to the paragraph.
paragraph = section.AddParagraph(); paragraph.AppendText("For more information, see "); paragraph.ChildObjects.Add(field);
Step 5: Insert a FieldSeparator object to the paragraph, which works as separator in a field.
FieldMark fieldSeparator= new FieldMark(doc, FieldMarkType.FieldSeparator); paragraph.ChildObjects.Add(fieldSeparator);
Step 6: Set the display text of the cross-reference field.
TextRange tr = new TextRange(doc); tr.Text = "above"; paragraph.ChildObjects.Add(tr);
Step 7: Insert a FieldEnd object to the paragraph, which is used to mark the end of a field.
FieldMark fieldEnd = new FieldMark(doc, FieldMarkType.FieldEnd); paragraph.ChildObjects.Add(fieldEnd);
Step 8: Save to file.
doc.SaveToFile("output.docx", FileFormat.Docx2013);
Output:
The cross-reference appears as a link that takes the reader to the referenced item.
Full Code:
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace CreatCR { class Program { static void Main(string[] args) { Document doc = new Document(); Section section = doc.AddSection(); //create a bookmark Paragraph paragraph = section.AddParagraph(); paragraph.AppendBookmarkStart("MyBookmark"); paragraph.AppendText("Text inside a bookmark"); paragraph.AppendBookmarkEnd("MyBookmark"); //insert line breaks for (int i = 0; i < 4; i++) { paragraph.AppendBreak(BreakType.LineBreak); } //create a cross-reference field, and link it to bookmark Field field = new Field(doc); field.Type = FieldType.FieldRef; field.Code = @"REF MyBookmark \p \h"; //insert field to paragraph paragraph = section.AddParagraph(); paragraph.AppendText("For more information, see "); paragraph.ChildObjects.Add(field); //insert FieldSeparator object FieldMark fieldSeparator = new FieldMark(doc, FieldMarkType.FieldSeparator); paragraph.ChildObjects.Add(fieldSeparator); //set display text of the field TextRange tr = new TextRange(doc); tr.Text = "above"; paragraph.ChildObjects.Add(tr); //insert FieldEnd object to mark the end of the field FieldMark fieldEnd = new FieldMark(doc, FieldMarkType.FieldEnd); paragraph.ChildObjects.Add(fieldEnd); //save file doc.SaveToFile("output.docx", FileFormat.Docx2013); } } }
Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Namespace CreatCR Class Program Private Shared Sub Main(args As String()) Dim doc As New Document() Dim section As Section = doc.AddSection() 'create a bookmark Dim paragraph As Paragraph = section.AddParagraph() paragraph.AppendBookmarkStart("MyBookmark") paragraph.AppendText("Text inside a bookmark") paragraph.AppendBookmarkEnd("MyBookmark") 'insert line breaks For i As Integer = 0 To 3 paragraph.AppendBreak(BreakType.LineBreak) Next 'create a cross-reference field, and link it to bookmark Dim field As New Field(doc) field.Type = FieldType.FieldRef field.Code = "REF MyBookmark \p \h" 'insert field to paragraph paragraph = section.AddParagraph() paragraph.AppendText("For more information, see ") paragraph.ChildObjects.Add(field) 'insert FieldSeparator object Dim fieldSeparator As New FieldMark(doc, FieldMarkType.FieldSeparator) paragraph.ChildObjects.Add(fieldSeparator) 'set display text of the field Dim tr As New TextRange(doc) tr.Text = "above" paragraph.ChildObjects.Add(tr) 'insert FieldEnd object to mark the end of the field Dim fieldEnd As New FieldMark(doc, FieldMarkType.FieldEnd) paragraph.ChildObjects.Add(fieldEnd) 'save file doc.SaveToFile("output.docx", FileFormat.Docx2013) End Sub End Class End Namespace
C# insert and remove TOC from the word document
We have already demonstrated how to add a brand new TOC when we create the word documents. This article will show you how to insert a TOC to the existing word documents with styles and remove the TOC from the word document.
Firstly, view the sample document with Title, Heading1 and Heading 2 styles:
The below code snippet shows how to insert a Table of contents (TOC) into a document.
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Text.RegularExpressions; namespace InsertTOC { class Program { static void Main(string[] args) { //Create a new instance of Document and load the document from file. Document doc = new Document(); doc.LoadFromFile("Sample.docx", FileFormat.Docx2010); //Add the TOC to the document TableOfContent toc = new TableOfContent(doc, "{\\o \"1-3\" \\h \\z \\u}"); Paragraph p = doc.LastSection.Paragraphs[0]; p.Items.Add(toc); p.AppendFieldMark(FieldMarkType.FieldSeparator); p.AppendText("TOC"); p.AppendFieldMark(FieldMarkType.FieldEnd); doc.TOC = toc; //Update the table of contents doc.UpdateTableOfContents(); //Save the document to file doc.SaveToFile("Result.docx", FileFormat.Docx); } } }
Removing a Table of Contents from the Document
using Spire.Doc; using System.Text.RegularExpressions; namespace RemoveTOC { class Program { static void Main(string[] args) { //load the document from file with TOC Document doc = new Document(); doc.LoadFromFile("Result.docx", FileFormat.Docx2010); //get the first body from the first section Body body = doc.Sections[0].Body; //remove TOC from first body Regex regex = new Regex("TOC\\w+"); for (int i = 0; i < body.Paragraphs.Count; i++) { if (regex.IsMatch(body.Paragraphs[i].StyleName)) { body.Paragraphs.RemoveAt(i); i--; } } //save the document to file doc.SaveToFile("RemoveTOC.docx", FileFormat.Docx2010); } } }
How to update Ask Field in C#
With Spire.Doc for .NET, developers can easily operate the word fields from code. We have already shown how to create an IF field and remove Custom Property Fields in C#. From Spire.Doc V5.8.33, our developers add a new event UpdateFields to handle the Ask Field. This article will focus on demonstrating how to update the ASK field on the word document in C#.
Firstly, please view the sample document with an Ask filed which will be updated later:
Step 1: Create a new instance of Spire.Doc.Document class and load the document from file.
Document doc = new Document(); doc.LoadFromFile("Sample.docx");
Step 2: Call UpdateFieldsHandler event to update the ASK field.
doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields);
Step 3: Update the fields in the document.
doc.IsUpdateFields = true;
Step 4: Save the document to file.
doc.SaveToFile("output.docx", FileFormat.Docx);
The following doc_UpdateFields () method shows how to update the ask field:
private static void doc_UpdateFields(object sender, IFieldsEventArgs args) { if (args is AskFieldEventArgs) { AskFieldEventArgs askArgs = args as AskFieldEventArgs; askArgs.ResponseText = "Female"; } }
Effective screenshot after updating the Ask Field in C#:
Full codes:
using Spire.Doc; using Spire.Doc.Fields; namespace Askfield { class Program { public void Field() { Document doc = new Document(); doc.LoadFromFile("Sample.docx"); doc.UpdateFields += new UpdateFieldsHandler(doc_UpdateFields); doc.IsUpdateFields = true; doc.SaveToFile("output.docx", FileFormat.Docx); } private static void doc_UpdateFields(object sender, IFieldsEventArgs args) { if (args is AskFieldEventArgs) { AskFieldEventArgs askArgs = args as AskFieldEventArgs; askArgs.ResponseText = "Female"; } } } }
How to Remove Custom Property Fields in C#, VB.NET
In our daily work, we may have the requirement to add custom properties with fields to a Word document. As is shown in the following Word document, I have created three custom property fields for easily inserting or updating information.
However, a custom property field may lose its value if we don’t want to use it any more, or a custom field might be created with wrong information, in such cases, we can choose to delete these fields manually and programmatically. In this article, I’ll introduce a C# and VB.NET solution to remove custom property fields using Spire.Doc.
Detailed Steps
Step 1: Create a new instance of Spire.Doc.Document class and load the sample file with specified path.
Document doc = new Document(); doc.LoadFromFile("FieldSample.docx", FileFormat.Docx);
Step 2: Get custom document properties object.
CustomDocumentProperties cdp = doc.CustomDocumentProperties;
Step 3: Use a for sentence and CustomDocumentProperties.Remove(string name) method to remove all custom property fields in the document.
for (int i = 0; i < cdp.Count; ) { cdp.Remove(cdp[i].Name); } doc.IsUpdateFields = true;
Step 4: Save the file.
doc.SaveToFile("Result.docx", FileFormat.Docx);
Output:
Full Code:
using Spire.Doc; namespace RemoveProperties { class Program { static void Main(string[] args) { Document doc = new Document(); doc.LoadFromFile("FieldSample.docx", FileFormat.Docx); CustomDocumentProperties cdp = doc.CustomDocumentProperties; for (int i = 0; i < cdp.Count; ) { cdp.Remove(cdp[i].Name); } doc.IsUpdateFields = true; doc.SaveToFile("Result.docx", FileFormat.Docx); } } }
Imports Spire.Doc Namespace RemoveProperties Class Program Private Shared Sub Main(args As String()) Dim doc As New Document() doc.LoadFromFile("FieldSample.docx", FileFormat.Docx) Dim cdp As CustomDocumentProperties = doc.CustomDocumentProperties Dim i As Integer = 0 While i < cdp.Count cdp.Remove(cdp(i).Name) End While doc.IsUpdateFields = True doc.SaveToFile("Result.docx", FileFormat.Docx) End Sub End Class End Namespace
How to create an IF field in C#
Usually we need to display different text and message to our readers based on the different conditions. In such situation, we need to create if field to decide which result to be displayed to readers. This article focuses on show you how to create an IF Field in C# with the help of Spire.Doc for .NET. We use the IF field and MERGEFIELD field together.
{IF { MERGEFIELD Count } > "100" "Thanks" "The minimum order is 100 units"}
Step 1: Create a new word document.
Document document = new Document();
Step 2: Add a new section for the document.
Section section = document.AddSection();
Step 3: Add a new paragraph for the section.
Paragraph paragraph = section.AddParagraph();
Step 4: Define a method of creating an IF Field.
CreateIfField(document, paragraph);
Step 5: Define merged data.
string[] fieldName = {"Count"}; string[] fieldValue = { "2" };
Step 6: Merge data into the IF Field.
document.MailMerge.Execute(fieldName, fieldValue);
Step 7: Update all fields in the document.
document.IsUpdateFields = true;
Step 8: Save the document to file.
document.SaveToFile("sample.docx", FileFormat.Docx);
The following CreateIfField() method shows how to create the IF Field like:
{IF { MERGEFIELD Count } > "100" "Thanks" " The minimum order is 100 units "}
static void CreateIfField(Document document, Paragraph paragraph) { IfField ifField = new IfField(document); ifField.Type = FieldType.FieldIf; ifField.Code = "IF "; paragraph.Items.Add(ifField); paragraph.AppendField("Count",FieldType.FieldMergeField); paragraph.AppendText(" > "); paragraph.AppendText("\"100\" "); paragraph.AppendText("\"Thanks\" "); paragraph.AppendText("\"The minimum order is 100 units\""); IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; paragraph.Items.Add(end); ifField.End = end as FieldMark; }
Check the effective screenshot as below:
Full Code:
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; namespace CreatIF { class Program { static void Main(string[] args) { Document document = new Document(); Section section = document.AddSection(); Paragraph paragraph = section.AddParagraph(); CreateIfField(document, paragraph); string[] fieldName = { "Count" }; string[] fieldValue = { "2" }; document.MailMerge.Execute(fieldName, fieldValue); document.IsUpdateFields = true; document.SaveToFile("sample.docx", FileFormat.Docx); } static void CreateIfField(Document document, Paragraph paragraph) { IfField ifField = new IfField(document); ifField.Type = FieldType.FieldIf; ifField.Code = "IF "; paragraph.Items.Add(ifField); paragraph.AppendField("Count", FieldType.FieldMergeField); paragraph.AppendText(" > "); paragraph.AppendText("\"100\" "); paragraph.AppendText("\"Thanks\" "); paragraph.AppendText("\"The minimum order is 100 units\""); IParagraphBase end = document.CreateParagraphItem(ParagraphItemType.FieldMark); (end as FieldMark).Type = FieldMarkType.FieldEnd; paragraph.Items.Add(end); ifField.End = end as FieldMark; } } }
Fill Form Fields in Word Document in C#
We have already demonstrated how to create form field. This article mainly shows you how developers fill form field in word document in C# only with 4 simple steps by using a standalone .NET Word component Spire.Doc.
Make sure Spire.Doc for .NET has been installed correctly and then add Spire.Doc.dll as reference in the downloaded Bin folder thought the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how developers Fill Form Field by using Spire.Doc:
Step 1: Open the form that needs to fill the data.
//Create word document Document document = new Document(@"..\..\..\Data\UserForm.doc");
Step 2: Load data that will fill the form.
//Fill data from XML file using (Stream stream = File.OpenRead(@"..\..\..\Data\User.xml")) { XPathDocument xpathDoc = new XPathDocument(stream); XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user");
Step 3: Use the loaded data to fill the form.
//fill data foreach (FormField field in document.Sections[0].Body.FormFields) { String path = String.Format("{0}/text()", field.Name); XPathNavigator propertyNode = user.SelectSingleNode(path); if (propertyNode != null) { switch (field.Type) { case FieldType.FieldFormTextInput: field.Text = propertyNode.Value; break; case FieldType.FieldFormDropDown: DropDownFormField combox = field as DropDownFormField; for(int i = 0; i < combox.DropDownItems.Count; i++) { if (combox.DropDownItems[i].Text == propertyNode.Value) { combox.DropDownSelectedIndex = i; break; } if (field.Name == "country" && combox.DropDownItems[i].Text == "Others") { combox.DropDownSelectedIndex = i; } } break; case FieldType.FieldFormCheckBox: if (Convert.ToBoolean(propertyNode.Value)) { CheckBoxFormField checkBox = field as CheckBoxFormField; checkBox.Checked = true; } break; } } } }
Step 4: Save the document to file in XML or Microsoft Word format.
//Save doc file document.SaveToFile("Sample.doc",FileFormat.Doc);
Effective Screenshot:
Full Source Code for Fill FormField:
namespace FillFormField { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //open form Document document = new Document(@"..\..\..\..\..\..\Data\UserForm.doc"); //load data using (Stream stream = File.OpenRead(@"..\..\..\..\..\..\Data\User.xml")) { XPathDocument xpathDoc = new XPathDocument(stream); XPathNavigator user = xpathDoc.CreateNavigator().SelectSingleNode("/user"); //fill data foreach (FormField field in document.Sections[0].Body.FormFields) { String path = String.Format("{0}/text()", field.Name); XPathNavigator propertyNode = user.SelectSingleNode(path); if (propertyNode != null) { switch (field.Type) { case FieldType.FieldFormTextInput: field.Text = propertyNode.Value; break; case FieldType.FieldFormDropDown: DropDownFormField combox = field as DropDownFormField; for(int i = 0; i < combox.DropDownItems.Count; i++) { if (combox.DropDownItems[i].Text == propertyNode.Value) { combox.DropDownSelectedIndex = i; break; } if (field.Name == "country" && combox.DropDownItems[i].Text == "Others") { combox.DropDownSelectedIndex = i; } } break; case FieldType.FieldFormCheckBox: if (Convert.ToBoolean(propertyNode.Value)) { CheckBoxFormField checkBox = field as CheckBoxFormField; checkBox.Checked = true; } break; } } } } //Save doc file. document.SaveToFile("Sample.doc",FileFormat.Doc); //Launching the MS Word file. WordDocViewer("Sample.doc"); } private void WordDocViewer(string fileName) { try { System.Diagnostics.Process.Start(fileName); } catch { } } } }
C#/VB.NET: Create a Fillable Form in Word
A form allows you to create placeholders for different types of information, such as text, dates, images and yes-no questions. This makes it easier for readers to know what type of information to include, and it also helps ensure all of the information is formatted the same way. In order to create a fillable form in Word, you will need to use the following tools.
- Content Controls: The areas where users input information in a form.
- Tables: Tables are used in forms to align text and form fields, and to create borders and boxes.
- Protection: Allows users to populate fields but not to make changes to the rest of the document.
Content controls in Word are containers for content that let users build structured documents. A structured document controls where content appears within the document. There are basically ten types of content controls available in Word 2013. This article focuses on how to create a fillable form in Word consisting of the following seven common content controls using Spire.Doc for .NET.
Content Control | Description |
Plain Text | A text field limited to plain text, so no formatting can be included. |
Rich Text | A text field that can contain formatted text or other items, such as tables, pictures, or other content controls. |
Picture | Accepts a single picture. |
Drop-Down List | A drop-down list displays a predefined list of items for the user to choose from. |
Combo Box | A combo box enables users to select a predefined value in a list or type their own value in the text box of the control. |
Check Box | A check box provides a graphical widget that allows the user to make a binary choice: yes (checked) or no (not checked). |
Date Picker | Contains a calendar control from which the user can select a date. |
Install Spire.Doc for .NET
To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.Doc
Create a Fillable Form in Word in C# and VB.NET
The StructureDocumentTagInline class provided by Spire.Doc for .NET is used to create structured document tags for inline-level structures (DrawingML object, fields, etc.) in a paragraph. The SDTProperties property and the SDTContent property under this class shall be used to specify the properties and content of the current structured document tag. The following are the detailed steps to create a fillable form with content controls in Word.
- Create a Document object.
- Add a section using Document.AddSection() method.
- Add a table using Section.AddTable() method.
- Add a paragraph to a specific table cell using TableCell.AddParagraph() method.
- Create an instance of StructureDocumentTagInline class, and add it to the paragraph as a child object using Paragraph.ChildObjects.Add() method.
- Specify the properties and content of the structured document tag though the SDTProperties property and the SDTContent property of the StructureDocumentTagInline object. The type of the structured document tag is set through SDTProperties.SDTType property.
- Prevent users from editing content outside form fields using Document.Protect() method.
- Save the document using Document.SaveToFile() method.
- C#
- VB.NET
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace CreateFormInWord { class Program { static void Main(string[] args) { //Create a Document object Document doc = new Document(); //Add a section Section section = doc.AddSection(); //add a table Table table = section.AddTable(true); table.ResetCells(7, 2); //Add text to the cells of the first column Paragraph paragraph = table.Rows[0].Cells[0].AddParagraph(); paragraph.AppendText("Plain Text Content Control"); paragraph = table.Rows[1].Cells[0].AddParagraph(); paragraph.AppendText("Rich Text Content Control"); paragraph = table.Rows[2].Cells[0].AddParagraph(); paragraph.AppendText("Picture Content Control"); paragraph = table.Rows[3].Cells[0].AddParagraph(); paragraph.AppendText("Drop-Down List Content Control"); paragraph = table.Rows[4].Cells[0].AddParagraph(); paragraph.AppendText("Check Box Content Control"); paragraph = table.Rows[5].Cells[0].AddParagraph(); paragraph.AppendText("Combo box Content Control"); paragraph = table.Rows[6].Cells[0].AddParagraph(); paragraph.AppendText("Date Picker Content Control"); //Add a plain text content control to the cell (0,1) paragraph = table.Rows[0].Cells[1].AddParagraph(); StructureDocumentTagInline sdt = new StructureDocumentTagInline(doc); paragraph.ChildObjects.Add(sdt); sdt.SDTProperties.SDTType = SdtType.Text; sdt.SDTProperties.Alias = "Plain Text"; sdt.SDTProperties.Tag = "Plain Text"; sdt.SDTProperties.IsShowingPlaceHolder = true; SdtText text = new SdtText(true); text.IsMultiline = false; sdt.SDTProperties.ControlProperties = text; TextRange tr = new TextRange(doc); tr.Text = "Click or tap here to enter text."; sdt.SDTContent.ChildObjects.Add(tr); //Add a rich text content control to the cell (1,1) paragraph = table.Rows[1].Cells[1].AddParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.ChildObjects.Add(sdt); sdt.SDTProperties.SDTType = SdtType.RichText; sdt.SDTProperties.Alias = "Rich Text"; sdt.SDTProperties.Tag = "Rich Text"; sdt.SDTProperties.IsShowingPlaceHolder = true; text = new SdtText(true); text.IsMultiline = false; sdt.SDTProperties.ControlProperties = text; tr = new TextRange(doc); tr.Text = "Click or tap here to enter text."; sdt.SDTContent.ChildObjects.Add(tr); //Add a picture content control to the cell (2,1) paragraph = table.Rows[2].Cells[1].AddParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.ChildObjects.Add(sdt); sdt.SDTProperties.SDTType = SdtType.Picture; sdt.SDTProperties.Alias = "Picture"; sdt.SDTProperties.Tag = "Picture"; SdtPicture sdtPicture = new SdtPicture(); sdt.SDTProperties.ControlProperties = sdtPicture; DocPicture pic = new DocPicture(doc); pic.LoadImage(Image.FromFile("C:\\Users\\Administrator\\Desktop\\ChooseImage.png")); sdt.SDTContent.ChildObjects.Add(pic); //Add a dropdown list content control to the cell(3,1) paragraph = table.Rows[3].Cells[1].AddParagraph(); sdt = new StructureDocumentTagInline(doc); sdt.SDTProperties.SDTType = SdtType.DropDownList; sdt.SDTProperties.Alias = "Dropdown List"; sdt.SDTProperties.Tag = "Dropdown List"; paragraph.ChildObjects.Add(sdt); SdtDropDownList sddl = new SdtDropDownList(); sddl.ListItems.Add(new SdtListItem("Choose an item.", "1")); sddl.ListItems.Add(new SdtListItem("Item 2", "2")); sddl.ListItems.Add(new SdtListItem("Item 3", "3")); sddl.ListItems.Add(new SdtListItem("Item 4", "4")); sdt.SDTProperties.ControlProperties = sddl; tr = new TextRange(doc); tr.Text = sddl.ListItems[0].DisplayText; sdt.SDTContent.ChildObjects.Add(tr); //Add two check box content controls to the cell (4,1) paragraph = table.Rows[4].Cells[1].AddParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.ChildObjects.Add(sdt); sdt.SDTProperties.SDTType = SdtType.CheckBox; SdtCheckBox scb = new SdtCheckBox(); sdt.SDTProperties.ControlProperties = scb; tr = new TextRange(doc); sdt.ChildObjects.Add(tr); scb.Checked = false; paragraph.AppendText(" Option 1"); paragraph = table.Rows[4].Cells[1].AddParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.ChildObjects.Add(sdt); sdt.SDTProperties.SDTType = SdtType.CheckBox; scb = new SdtCheckBox(); sdt.SDTProperties.ControlProperties = scb; tr = new TextRange(doc); sdt.ChildObjects.Add(tr); scb.Checked = false; paragraph.AppendText(" Option 2"); //Add a combo box content control to the cell (5,1) paragraph = table.Rows[5].Cells[1].AddParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.ChildObjects.Add(sdt); sdt.SDTProperties.SDTType = SdtType.ComboBox; sdt.SDTProperties.Alias = "Combo Box"; sdt.SDTProperties.Tag = "Combo Box"; SdtComboBox cb = new SdtComboBox(); cb.ListItems.Add(new SdtListItem("Choose an item.")); cb.ListItems.Add(new SdtListItem("Item 2")); cb.ListItems.Add(new SdtListItem("Item 3")); sdt.SDTProperties.ControlProperties = cb; tr = new TextRange(doc); tr.Text = cb.ListItems[0].DisplayText; sdt.SDTContent.ChildObjects.Add(tr); //Add a date picker content control to the cell (6,1) paragraph = table.Rows[6].Cells[1].AddParagraph(); sdt = new StructureDocumentTagInline(doc); paragraph.ChildObjects.Add(sdt); sdt.SDTProperties.SDTType = SdtType.DatePicker; sdt.SDTProperties.Alias = "Date Picker"; sdt.SDTProperties.Tag = "Date Picker"; SdtDate date = new SdtDate(); date.CalendarType = CalendarType.Default; date.DateFormat = "yyyy.MM.dd"; date.FullDate = DateTime.Now; sdt.SDTProperties.ControlProperties = date; tr = new TextRange(doc); tr.Text = "Click or tap to enter a date."; sdt.SDTContent.ChildObjects.Add(tr); //Allow users to edit the form fields only doc.Protect(ProtectionType.AllowOnlyFormFields, "permission-psd"); //Save to file doc.SaveToFile("WordForm.docx", FileFormat.Docx2013); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.