Bookmarks are a great way to specify important locations on a Word document. Spire.Doc supports to access the bookmarks within the document and insert objects such as text, image and table at the bookmark location. This article will show you how to access a specific bookmark and replace the current bookmark content with a table.

Step 1: Load a template Word document.

Document doc = new Document();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\employee.docx");

Step 2: Create a Table object.

Table table = new Table(doc,true);

Step 3: Fill the table with sample data.

DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("name", typeof(string));
dt.Columns.Add("job", typeof(string));
dt.Columns.Add("email", typeof(string));
dt.Columns.Add("salary", typeof(string));
dt.Rows.Add(new string[] { "Emp_ID", "Name", "Job", "E-mail", "Salary" });
dt.Rows.Add(new string[] { "0241","Andrews", "Engineer", "andrews@outlook.com" ,"3.8K"});
dt.Rows.Add(new string[] { "0242","White", "Manager", "white@outlook.com","4.2K" });
dt.Rows.Add(new string[] { "0243","Martin", "Secretary", "martin@gmail.com", "3.5K" });
table.ResetCells(dt.Rows.Count, dt.Columns.Count);          
for (int i = 0; i < dt.Rows.Count; i++)
{
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        table.Rows[i].Cells[j].AddParagraph().AppendText(dt.Rows[i][j].ToString());
    }
}

Step 4: Get the specific bookmark by its name.

BookmarksNavigator navigator = new BookmarksNavigator(doc);
navigator.MoveToBookmark("bookmark_employee");

Step 5: Create a TextBodyPart instance and add the table to it.

TextBodyPart part = new TextBodyPart(doc);
part.BodyItems.Add(table);

Step 6: Replace the current bookmark content with the TextBodyPart object.

navigator.ReplaceBookmarkContent(part);

Step 7: Save the file.

doc.SaveToFile("output.docx", FileFormat.Docx2013);

Result:

Replace Bookmark with a Table in Word Documents in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using System.Data;
namespace ReplaceBookmark
{
    class Program
    {

        static void Main(string[] args)
        {

            Document doc = new Document();
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\employee.docx");

            Table table = new Table(doc, true);
            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(string));
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("job", typeof(string));
            dt.Columns.Add("email", typeof(string));
            dt.Columns.Add("salary", typeof(string));
            dt.Rows.Add(new string[] { "Emp_ID", "Name", "Job", "E-mail", "Salary" });
            dt.Rows.Add(new string[] { "0241", "Andrews", "Engineer", "andrews@outlook.com", "3.8K" });
            dt.Rows.Add(new string[] { "0242", "White", "Manager", "white@outlook.com", "4.2K" });
            dt.Rows.Add(new string[] { "0243", "Martin", "Secretary", "martin@gmail.com", "3.5K" });
            table.ResetCells(dt.Rows.Count, dt.Columns.Count);
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    table.Rows[i].Cells[j].AddParagraph().AppendText(dt.Rows[i][j].ToString());
                }
            }

            BookmarksNavigator navigator = new BookmarksNavigator(doc);
            navigator.MoveToBookmark("bookmark_employee");
            TextBodyPart part = new TextBodyPart(doc);
            part.BodyItems.Add(table);
            navigator.ReplaceBookmarkContent(part);
            doc.SaveToFile("output.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("output.docx"); 

        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Data
Namespace ReplaceBookmark
	Class Program

		Private Shared Sub Main(args As String())

			Dim doc As New Document()
			doc.LoadFromFile("C:\Users\Administrator\Desktop\employee.docx")

			Dim table As New Table(doc, True)
			Dim dt As New DataTable()
			dt.Columns.Add("id", GetType(String))
			dt.Columns.Add("name", GetType(String))
			dt.Columns.Add("job", GetType(String))
			dt.Columns.Add("email", GetType(String))
			dt.Columns.Add("salary", GetType(String))
			dt.Rows.Add(New String() {"Emp_ID", "Name", "Job", "E-mail", "Salary"})
			dt.Rows.Add(New String() {"0241", "Andrews", "Engineer", "andrews@outlook.com", "3.8K"})
			dt.Rows.Add(New String() {"0242", "White", "Manager", "white@outlook.com", "4.2K"})
			dt.Rows.Add(New String() {"0243", "Martin", "Secretary", "martin@gmail.com", "3.5K"})
			table.ResetCells(dt.Rows.Count, dt.Columns.Count)
			For i As Integer = 0 To dt.Rows.Count - 1
				For j As Integer = 0 To dt.Columns.Count - 1
					table.Rows(i).Cells(j).AddParagraph().AppendText(dt.Rows(i)(j).ToString())
				Next
			Next

			Dim navigator As New BookmarksNavigator(doc)
			navigator.MoveToBookmark("bookmark_employee")
			Dim part As New TextBodyPart(doc)
			part.BodyItems.Add(table)
			navigator.ReplaceBookmarkContent(part)
			doc.SaveToFile("output.docx", FileFormat.Docx2013)
			System.Diagnostics.Process.Start("output.docx")

		End Sub
	End Class
End Namespace
Published in Bookmark
Wednesday, 03 January 2018 08:44

Get Text within a Bookmark in C#, VB.NET

Spire.Doc supports to retrieve, replace and delete bookmark content of a specified bookmark. This article will show you how we can get the plain text within a bookmark by using Spire.Doc with C# and VB.NET.

Step 1: Create a Document instance, and load a sample Word document.

Document doc = new Document();
doc.LoadFromFile("Bookmark.docx");

Step 2: Creates a BookmarkNavigator instance to access the bookmark.

BookmarksNavigator navigator = new BookmarksNavigator(doc);

Step 3: Locate a specific bookmark by bookmark name. Call the method GetBookmarkContent to get content within the bookmark.

navigator.MoveToBookmark("bookmark_1");
TextBodyPart textBodyPart = navigator.GetBookmarkContent();

Step 4: Iterate through the items in the bookmark content to get the plain, unformatted text of the bookmark.

string text = null;
foreach (var item in textBodyPart.BodyItems)
{
    if (item is Paragraph)
    {
        foreach (var childObject in (item as Paragraph).ChildObjects)
        {
            if (childObject is TextRange)
            {
                text += (childObject as TextRange).Text;
            }
        }
    }
}

Result:

Get Text within a Bookmark in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
namespace GetText
{
    class Program
    {

        static void Main(string[] args)
        {

            Document doc = new Document();
            doc.LoadFromFile("Bookmark.docx");

            BookmarksNavigator navigator = new BookmarksNavigator(doc);
            navigator.MoveToBookmark("bookmark_1");
            TextBodyPart textBodyPart = navigator.GetBookmarkContent();

            string text = null;
            foreach (var item in textBodyPart.BodyItems)
            {
                if (item is Paragraph)
                {
                    foreach (var childObject in (item as Paragraph).ChildObjects)
                    {
                        if (childObject is TextRange)
                        {
                            text += (childObject as TextRange).Text;
                        }
                    }
                }
            }
            Console.WriteLine(text);
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Namespace GetText
	Class Program

		Private Shared Sub Main(args As String())

			Dim doc As New Document()
			doc.LoadFromFile("Bookmark.docx")

			Dim navigator As New BookmarksNavigator(doc)
			navigator.MoveToBookmark("bookmark_1")
			Dim textBodyPart As TextBodyPart = navigator.GetBookmarkContent()

			Dim text As String = Nothing
			For Each item As var In textBodyPart.BodyItems
				If TypeOf item Is Paragraph Then
					For Each childObject As var In TryCast(item, Paragraph).ChildObjects
						If TypeOf childObject Is TextRange Then
							text += TryCast(childObject, TextRange).Text
						End If
					Next
				End If
			Next
			Console.WriteLine(text)
		End Sub
	End Class
End Namespace
Published in Bookmark

We have already demonstrated how to insert single bookmark to word document by using Spire.Doc. When you need to insert many bookmarks to long word document, you can also use Spire.Doc to add multiple levels bookmarks and set different colors for them. Spire.Doc Version 5.5.71 adds a new method of BookmarkLayout to enable developers to set the different color for the different levels of bookmarks. This article will show you how to set the different color for the different levels of bookmarks.

Here comes to the code snippet:

Step 1: Create a new word document and load a file with nested level bookmarks.

Document document = new Document();
document.LoadFromFile("sample.docx");

Step 2: Save the word document into PDF to view the effects clearly and add the event of BookmarkLayout before saving to PDF.

ToPdfParameterList toPdf = new ToPdfParameterList();
toPdf.CreateWordBookmarks = true;
toPdf.WordBookmarksTitle = "Changed bookmark";
toPdf.WordBookmarksColor = Color.Gray;

//the event of BookmarkLayout occurs when draw a bookmark
document.BookmarkLayout += new Spire.Doc.Documents.Rendering.BookmarkLevelHandler(document_BookmarkLayout);

document.SaveToFile("result.pdf", toPdf);

Step 3: Call the method of BookmarkLayout to set the different color for the different levels of bookmarks.

static void document_BookmarkLayout(object sender, Spire.Doc.Documents.Rendering.BookmarkLevelEventArgs args)
{
    
    //set the different color for different levels of bookmarks
    if (args.BookmarkLevel.Level == 2)
    {
        args.BookmarkLevel.Color = Color.Red;
        args.BookmarkLevel.Style = BookmarkTextStyle.Bold;
    }
    else if (args.BookmarkLevel.Level == 3)
    {
        args.BookmarkLevel.Color = Color.Gray;
        args.BookmarkLevel.Style = BookmarkTextStyle.Italic;
    }
    else
    {
        args.BookmarkLevel.Color = Color.Green;
        args.BookmarkLevel.Style = BookmarkTextStyle.Regular;
    }

Please check the effective screenshot of multiple levels bookmarks with different colors:

How to set the color for different levels bookmark in word documents

Full codes:

using Spire.Doc;
using System.Drawing;
namespace SetColor
{
    class Program
    {

        static void Main(string[] args)
        {

            Document document = new Document();
            document.LoadFromFile("sample.docx");

            ToPdfParameterList toPdf = new ToPdfParameterList();
            toPdf.CreateWordBookmarks = true;
            toPdf.WordBookmarksTitle = "Changed bookmark";
            toPdf.WordBookmarksColor = Color.Gray;

            //the event of BookmarkLayout occurs when draw a bookmark
            document.BookmarkLayout += new Spire.Doc.Documents.Rendering.BookmarkLevelHandler(document_BookmarkLayout);

            document.SaveToFile("result.pdf", toPdf);
        }
        static void document_BookmarkLayout(object sender, Spire.Doc.Documents.Rendering.BookmarkLevelEventArgs args)
        {

            if (args.BookmarkLevel.Level == 2)
            {
                args.BookmarkLevel.Color = Color.Red;
                args.BookmarkLevel.Style = BookmarkTextStyle.Bold;
            }
            else if (args.BookmarkLevel.Level == 3)
            {
                args.BookmarkLevel.Color = Color.Gray;
                args.BookmarkLevel.Style = BookmarkTextStyle.Italic;
            }
            else
            {
                args.BookmarkLevel.Color = Color.Green;
                args.BookmarkLevel.Style = BookmarkTextStyle.Regular;
            }
        }
    }
}
Published in Bookmark

Word bookmarks are widely used for point out a specified location or give brief information of the paragraph. If you add an image into the bookmark position, the bookmarks will be more obviously and clearly. This article will show you how to insert an image at bookmark position in C# with the help of Spire.Doc.

Spire.Doc offers an instance of BookmarksNavigator to find the bookmarks, and then developers use AppendPicture to add an image. Here comes to the steps:

Step 1: Load a word documents with bookmarks.

Document document = new Document();
document.LoadFromFile("Test.docx");

Step 2: Create an instance of BookmarksNavigator and find the bookmark where you want to insert an image.

//Create an instance of BookmarksNavigator
BookmarksNavigator bn = new BookmarksNavigator(document);
//Find a bookmark and its name is Spire
bn.MoveToBookmark("Spire", true, true);

Step 3: Insert an image at the position of bookmarks you found.

//Add a section and named it section0
Section section0 = document.AddSection();
//Add a paragraph for section0
Paragraph paragraph = section0.AddParagraph();
Image image = Image.FromFile("step.png");
//Add a picture into paragraph
DocPicture picture = paragraph.AppendPicture(image);
//Add a paragraph with picture at the position of bookmark
bn.InsertParagraph(paragraph);
document.Sections.Remove(section0);

Step 4: Save the new document and process it.

string output = "sample3.docx";
document.SaveToFile(output, FileFormat.Docx);
System.Diagnostics.Process.Start(output);

Spire.Doc also offers the following properties to set the image position based on developers' requirements.

picture.TextWrappingStyle
picture.HorizontalAlignment
picture.HorizontalOrigin
picture.HorizontalPosition
picture.VerticalAlignment
picture.VerticalOrigin
picture.VerticalPosition

Effective screenshot:

Insert an image at bookmark in word documents

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace InsertImage
{
    class Program
    {

        static void Main(string[] args)
        {

            Document document = new Document();
            document.LoadFromFile("Test.docx");
            BookmarksNavigator bn = new BookmarksNavigator(document);
            bn.MoveToBookmark("Spire", true, true);
            Section section0 = document.AddSection();
            Paragraph paragraph = section0.AddParagraph();
            Image image = Image.FromFile("step.png");
            DocPicture picture = paragraph.AppendPicture(image);
            bn.InsertParagraph(paragraph);
            document.Sections.Remove(section0);
            string output = "sample.docx";
            document.SaveToFile(output, FileFormat.Docx);
            System.Diagnostics.Process.Start(output);
        }
    }
}
Published in Bookmark

Bookmarks give convenience when users want go to specified location and it is clearly to know the contents brief information. Spire.Doc for .NET has a powerful function of operating the word elements of bookmarks. Developers can add bookmarks, Edit/replace bookmarks and remove bookmarks in word documents. Now Spire.Doc starts to support preserve bookmarks in DOCX to PDF conversion. This article will show you how to preserve bookmarks in C# when converting word document into PDF file format.

Download and install Spire.Doc for .NET (Version 5.2.20 or above) and then add Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Here comes to the details of how to preserve the bookmarks from word to PDF conversion in C#.

Step 1: Load a word documents with bookmarks.

Document doc = new Document();
doc.LoadFromFile("test.docx", FileFormat.Docx);

Step 2: Create an instance of ToPdfParameterList

ToPdfParameterList toPdf = new ToPdfParameterList();

Step 3: Set CreateWordBookmarks to true to use word bookmarks when create the bookmarks.

toPdf.CreateWordBookmarks = true;

Step 4: Save the PDF file.

doc.SaveToFile("test.Pdf",toPdf);

Effective screenshot of preserve the bookmarks in result PDF page:

Preserve bookmarks in PDF from word

Full codes:

[C#]
using Spire.Doc;
namespace PreventBookmark
{
    class Program
    {

        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("test.docx", FileFormat.Docx);
            ToPdfParameterList toPdf = new ToPdfParameterList();
            toPdf.CreateWordBookmarks = true;
            doc.SaveToFile("test.Pdf", toPdf);
            System.Diagnostics.Process.Start("test.Pdf");

        }
    }
}
Published in Bookmark

Bookmark can locate a range. Assuming the content of the range is some html code, how to change the content of the range. Spire.Doc supports bookmarks. And you can use Spire.Doc to fulfill the job.

In this article, a solution will be introduced. Spire.Doc provides you a method:

[C#]
public void ReplaceBookmarkContent(TextBodyPart bodyPart)

Replace the content of bookmark with TextBodyPart bodyPart.

This method cannot handle html code directly. Here is what to do. First load the new html code to document. Then select the newly added data as TextBodyPart. At last, call the method to replace the content of the bookmark.

Step 1: Add bookmarks containing html code.

[C#]
Paragraph p2 = section.AddParagraph();
p2.AppendBookmarkStart("bookmark2");
p2.AppendHTML("<p><font color='blue'>This para is also Generated by Decoding HTML Code</font></p>");
p2.AppendBookmarkEnd("bookmark2");

Step 2: Add new html code to document.

[C#]
Section tempSection = document.AddSection();
String html
= "<p>This Bookmark has been <font color=\"#ff0000\">Edited</font></p>";
tempSection.AddParagraph().AppendHTML(html);

Step 3: Get the new added html as TextBodyPart.

[C#]
ParagraphBase replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase;
ParagraphBase replacementLastItem  = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase;
TextBodySelection selection = new TextBodySelection(replacementFirstItem, replacementLastItem);
TextBodyPart part = new TextBodyPart(selection);

Step 4: Locate the bookmark "bookmark2" and call the method ReplaceBookmarkContent to replace the content. Then remove the temp section.

[C#]
BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
//locate the bookmark
bookmarkNavigator.MoveToBookmark("bookmark2");
//replace the content of bookmark
bookmarkNavigator.ReplaceBookmarkContent(part);
//remove temp section
document.Sections.Remove(tempSection);

Preview the original screenshot:

Edit and replace bookmark with HTML

Preview the effect screenshot:

Edit and replace bookmark with HTML

Here comes to the full code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;
namespace EditContent
{
    class Program
    {

        static void Main(string[] args)
        {
            Document document = new Document();
            Section section = document.AddSection();

            //create bookmarks
            Paragraph p1 = section.AddParagraph();
            p1.AppendBookmarkStart("bookmark1");
            p1.AppendHTML("

This para is also Generated by Decoding HTML Code

"); p1.AppendBookmarkEnd("bookmark1"); Paragraph p2 = section.AddParagraph(); p2.AppendBookmarkStart("bookmark2"); p2.AppendHTML("

This para is also Generated by Decoding HTML Code

"); p2.AppendBookmarkEnd("bookmark2"); document.SaveToFile("BeforeReplace.doc"); //create a temp section to contain multiple paragraph. Section tempSection = document.AddSection(); String html = "

This Bookmark has been Edited

"; tempSection.AddParagraph().AppendHTML(html); ParagraphBase replacementFirstItem = tempSection.Paragraphs[0].Items.FirstItem as ParagraphBase; ParagraphBase replacementLastItem = tempSection.Paragraphs[tempSection.Paragraphs.Count - 1].Items.LastItem as ParagraphBase; TextBodySelection selection = new TextBodySelection(replacementFirstItem, replacementLastItem); TextBodyPart part = new TextBodyPart(selection); BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); //locate the bookmark bookmarkNavigator.MoveToBookmark("bookmark2"); //replace the content of bookmark bookmarkNavigator.ReplaceBookmarkContent(part); //remove temp section document.Sections.Remove(tempSection); document.SaveToFile(@"AfterReplace.doc"); } } }
Published in Bookmark

Bookmarks in Microsoft Word are useful for quickly navigating to specific sections of a document. They allow you to create and name "markers" within your document that you can easily jump to. This can be particularly helpful when working with long or complex documents.

In this article, you will learn how to add and remove bookmarks in a Word document using C# and the Spire.Doc for .NET library.

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

Add a Bookmark to a Paragraph in C#

Using Spire.Doc, you can create a bookmark for a paragraph by inserting a BookmarkStart object at the beginning of the paragraph and a BookmarkEnd object at the end of the paragraph. The space between the bookmark start and end points becomes a defined bookmark that can be referenced and accessed as needed.

The detailed steps to add a bookmark to a paragraph are as follows.

  • Create a Document object.
  • Load a Word document.
  • Get a specific paragraph from a specified section.
  • Create a BookmarkStart object using Paragraph.AppendBookmarkStart() method.
  • Insert the BookmarkStart at the beginning of the selected paragraph.
  • Append a BookmarkEnd object to the end of the paragraph using Paragraph.AppendBookmarkEnd() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace AddBookmarkToParagraph
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Get a specified paragraph
            Paragraph paragraph = doc.Sections[0].Paragraphs[2];

            // Create a bookmark start
            BookmarkStart start = paragraph.AppendBookmarkStart("myBookmark");

            // Insert it at the beginning of the paragraph
            paragraph.Items.Insert(0, start);

            // Append a bookmark end at the end of the paragraph
            paragraph.AppendBookmarkEnd("myBookmark");

            // Save the file
            doc.SaveToFile("AddBookmarkToParagraph.docx", FileFormat.Docx2019);

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add or Remove Bookmarks in Word Documents

Add a Bookmark to Specific Text within a Paragraph in C#

To add a bookmark to specific text, you need first to find the text and its position within the paragraph. Then, insert a BookmarkStart object before the text and a BookmarkEnd object after the text.

The following are the steps to add a bookmark to specific text within a paragraph using Spire.Doc.

  • Create a Document object.
  • Load a Word document.
  • Find the desired text from the document, and get its position in its owner paragraph.
  • Create a BookmarkStart object using Paragraph.AppendBookmarkStart() method.
  • Insert the BookmarkStart before the selected text.
  • Create a BookmarkEnd object using Paragraph.AppendBookmarkEnd() method.
  • Insert the BookmarkEnd object behind the selected text.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;

namespace AddBookmarkToText
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a Document object
            Document doc = new Document();

            // Load a Word file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\input.docx");

            // Specify the string to find
            string stringToFind = "Privacy Policy";

            // Find the selected text from the document
            TextSelection[] finds = doc.FindAllString(stringToFind, false, true);
            TextSelection specificText = finds[1];

            // Find the paragraph where the text is located
            Paragraph para = specificText.GetAsOneRange().OwnerParagraph;

            // Get the index of the text in the paragraph
            int index = para.ChildObjects.IndexOf(specificText.GetAsOneRange());

            // Create a bookmark start
            BookmarkStart start = para.AppendBookmarkStart("myBookmark");

            // Insert the bookmark start at the index position
            para.ChildObjects.Insert(index, start);

            // Create a bookmark end
            BookmarkEnd end = para.AppendBookmarkEnd("myBookmark");

            // Insert the bookmark end at the end of the selected text
            para.ChildObjects.Insert(index + 2, end);

            // Save the document to another file
            doc.SaveToFile("AddBookmarkToText.docx", FileFormat.Docx2019);

            // Dispose resources
            doc.Dispose();
        }
    }
}

C#: Add or Remove Bookmarks in Word Documents

Remove Bookmarks from a Word Document in C#

To remove a specific bookmark or all bookmarks from a Word document, you can use the Bookmarks.Remove() method or the Bookmarks.Clear() method. The detailed steps are as follows.

  • Create a Document object.
  • Load a Word document.
  • Get a specific bookmark from the document by its index using Document.Bookmarks[index] property.
  • Remove the bookmark using Bookmarks.Remove() method.
  • To remove all bookmarks at once, use Document.Bookmarks.Clear() method.
  • Save the document to a different Word file.
  • C#
using Spire.Doc;

namespace RemoveBookmarks
{
    class Program
    {
        static void Main(string[] args)
        {

            // Create a Document object
            Document doc = new Document();

            // Load a Word file
            doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\Bookmarks.docx");

            // Get a specific bookmark by its index
            Bookmark bookmark = doc.Bookmarks[0];

            // Remove the bookmark
            doc.Bookmarks.Remove(bookmark);

            // Remove all bookmarks at once
            // doc.Bookmarks.Clear();

            // Save the document.
            doc.SaveToFile("RemoveBookmark.docx", FileFormat.Docx2019);

            // 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.

Published in Bookmark