How to Add Bookmark in Word using C#

This quick tutorial explains how to add bookmark in Word using C#. It explains the process to add bookmarks and one or more nested bookmarks in the Word file and then saving the resultant document as a DOCX file. All the necessary steps, resources, and a runnable sample code to automatically create bookmarks in Word using C# are also available in this article.

Steps to Add Bookmark in Word using C#

  1. Establish the environment to use Aspose.Words for .NET for adding the bookmark
  2. Create a new document using the Document class object for inserting bookmarks
  3. Instantiate DocumentBuilder for adding text and bookmarks
  4. Start a bookmark and add some text after it
  5. Add more bookmarks and text and end the internal bookmark
  6. End the external bookmark and save the resultant file on the disk

These steps describe the process to create bookmark in Word using C#. First, an empty Word file is created and then a bookmark is added followed by some text to test the feature in the resultant output file. Afterward a nested bookmark is added for more clarity and then the external bookmark is also ended to demonstrate the complete feature.

Code to Add Bookmark to Word Document using C#

using Aspose.Words;
namespace AsposeProjects
{
class Program
{
static void Main(string[] args) // Main function to add bookmark in Word document using C#
{
// Initialize license
License lic = new License();
lic.SetLicense("Aspose.Total.lic");
// Create a new document
Document doc = new Document();
// Create a document builder object
DocumentBuilder builder = new DocumentBuilder(doc);
// Start a bookmark and add some text
builder.StartBookmark("My Bookmark");
builder.Writeln("Text inside a bookmark.");
// Start and end a nested bookmark with some text
builder.StartBookmark("Nested Bookmark");
builder.Writeln("Text inside a NestedBookmark.");
builder.EndBookmark("Nested Bookmark");
// Write text after the nested bookmark and end the external bookmark
builder.Writeln("Text after Nested Bookmark.");
builder.EndBookmark("My Bookmark");
doc.Save("Output.docx");
System.Console.WriteLine("Done");
}
}
}

This sample code demonstrates the process to insert a bookmark in Word using C#. The DocumentBuilder.StartBookmark() method is used to start a bookmark that requires the name of the bookmark as an argument. Similarly, EndBookmark() method is used to set the end of the bookmark by providing the name of the bookmark as an argument that is to be closed.

In this article, we have learned the process to add one or more bookmarks in a Word file. If you want to learn the process to insert headers and footers, then refer to the article on how to insert header and footer in DOCX using C#.

 English