Knowledgebase (2344)
Children categories
Document Tree Traversal
using System;
using System.Collections.Generic;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Interface;
using Spire.Doc.Collections;
namespace ExtractText
{
class Program
{
static void Main(string[] args)
{
//Open a word document.
Document document = new Document("Sample.doc");
IList<IDocumentObject> nodes = GetAllObjects(document);
foreach (IDocumentObject node in nodes)
{
//Judge the object type.
if (node.DocumentObjectType == DocumentObjectType.TextRange)
{
TextRange textNode = node as TextRange;
Console.WriteLine(textNode.Text);
}
}
}
private static IList<IDocumentObject> GetAllObjects(Document document)
{
//Create a list.
List<IDocumentObject> nodes = new List<IDocumentObject>();
//Create a new queue.
Queue<ICompositeObject> containers = new Queue<ICompositeObject>();
//Put the document objects in the queue.
containers.Enqueue(document);
while (containers.Count > 0)
{
ICompositeObject container = containers.Dequeue();
DocumentObjectCollection docObjects = container.ChildObjects;
foreach (DocumentObject docObject in docObjects)
{
nodes.Add(docObject);
//Judge the docObject.
if (docObject is ICompositeObject)
{
containers.Enqueue(docObject as ICompositeObject);
}
}
}
return nodes;
}
}
}
Imports System
Imports System.Collections.Generic
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Doc.Interface
Imports Spire.Doc.Collections
Module Module1
Sub Main()
'Open a word document.
Dim document As New Document("Sample.doc")
Dim nodes As IList(Of IDocumentObject)() = GetAllObjects(document)
Dim containers As New Queue(Of ICompositeObject)()
For Each node As IDocumentObject In nodes
'Judge the object type.
If (node.DocumentObjectType = DocumentObjectType.TextRange) Then
Dim textNode As TextRange = node
Console.WriteLine(textNode.Text)
End If
Next
End Sub
Function GetAllObjects(ByVal document As Document) As IList(Of IDocumentObject)
'Create a list.
Dim nodes As New List(Of IDocumentObject)()
'Create a new queue.
Dim containers As New Queue(Of ICompositeObject)()
'Put the document objects in the queue.
containers.Enqueue(document)
While (containers.Count > 0)
Dim container As ICompositeObject = containers.Dequeue()
Dim docObjects As DocumentObjectCollection = container.ChildObjects
For Each docObject As DocumentObject In docObjects
nodes.Add(docObject)
'Judge the docObject.
If TypeOf docObject Is ICompositeObject Then
containers.Enqueue(TryCast(docObject, ICompositeObject))
End If
Next
End While
Return nodes
End Function
End Module
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.
- Add a Bookmark to a Paragraph in C#
- Add a Bookmark to Specific Text within a Paragraph in C#
- Remove Bookmarks from a Word Document in C#
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();
}
}
}

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();
}
}
}

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.
In Word documents, you can add time, date, title, reference information, page number, content description and image /logo in header or footer to enrich the document. This article shows how to add headers and footers in C# and VB.NET applications using Spire.Doc for .NET.
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 DLLs files can be either downloaded from this link or installed via NuGet.
- Package Manager
PM> Install-Package Spire.Doc
Add Header and Footer
The table gives a list of main classes, properties and methods used in the operation.
| Name | Description |
| Document Class | Represents a Word document model. |
| Document. LoadFromFile() Method | Load a Word document. |
| Section Class | Represents a section in a Word document. |
| Document.Sections Property | Gets document sections. |
| HeaderFooter Class | Represents a header and footer model for Word. |
| Section.HeadersFooters.Header Property | Gets headers/footers of current section. |
| Paragraph Class | Represents a paragraph in a document. |
| HeaderFooter. AddParagraph() Method | Adds paragraph at end of section. |
| TextRange Class | Represents a text range. |
| Paragraph.AppendText() Method | Appends text to the end of paragraph. |
| Document. SaveToFile() Method | Saves the document to file in Microsoft Word or another file format. |
The following are the steps about adding header and footer.
- Create an instance of Document class.
- Load the sample document using Document.LoadFromFile(string fileName) method.
- Get the specified section of Word Document using Document.Sections Property
- Add Header
- Get header using HeadersFooters.Header property.
- Add paragraph using HeaderFooter. AddParagraph() method and set paragraph alignment.
- Append text using Paragraph.AppendText(string text) method and set font name, size, color ,etc.
- Add Footer
- Get footer using HeadersFooters.Footer proterty.
- Add paragraph and text in footer.
- Save Word document using Document. SaveToFile(string filename, FileFormat fileFormat) method.
- C#
- VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using Spire.Doc.Fields;
namespace AddHeaderAndFooter
{
class Program
{
static void Main(string[] args)
{
//Create an instance of Document class
Document document = new Document();
//Load a Word document
document.LoadFromFile("input.docx");
//Get the first section of Word Document
Section section = document.Sections[0];
//Get header via HeadersFooters.Header property
HeaderFooter header = section.HeadersFooters.Header;
//Add a paragraph and set paragraph alignment style
Paragraph headerPara = header.AddParagraph();
headerPara.Format.HorizontalAlignment = HorizontalAlignment.Left;
//Append text and set font name, size, color,etc.
TextRange textrange = headerPara.AppendText("E-iceblue Co. Ltd." + "\n Your Office Development Master");
textrange.CharacterFormat.FontName = "Arial";
textrange.CharacterFormat.FontSize = 13;
textrange.CharacterFormat.TextColor = Color.DodgerBlue;
textrange.CharacterFormat.Bold = true;
//Get footer, add paragraph and append text
HeaderFooter footer = section.HeadersFooters.Footer;
Paragraph footerPara = footer.AddParagraph();
footerPara.Format.HorizontalAlignment = HorizontalAlignment.Center;
textrange = footerPara.AppendText("Copyright © 2021 All Rights Reserved.");
textrange.CharacterFormat.Bold = false;
textrange.CharacterFormat.FontSize = 11;
//Save to file
document.SaveToFile("output.docx", FileFormat.Docx);
}
}
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.Drawing
Imports Spire.Doc.Fields
Namespace AddHeaderAndFooter
Class Program
Private Shared Sub Main(args As String())
'Create an instance of Document class
Dim document As New Document()
'Load a Word document
document.LoadFromFile("input.docx")
'Get the first section of Word Document
Dim section As Section = document.Sections(0)
'Get header via HeadersFooters.Header property
Dim header As HeaderFooter = section.HeadersFooters.Header
'Add a paragraph and set paragraph alignment style
Dim headerPara As Paragraph = header.AddParagraph()
headerPara.Format.HorizontalAlignment = HorizontalAlignment.Left
'Append text and set font name, size, color ,etc.
Dim textrange As TextRange = headerPara.AppendText("E-iceblue Co. Ltd." + vbLf & " Your Office Development Master")
textrange.CharacterFormat.FontName = "Arial"
textrange.CharacterFormat.FontSize = 13
textrange.CharacterFormat.TextColor = Color.DodgerBlue
textrange.CharacterFormat.Bold = True
'Get footer, add paragraph and append text
Dim footer As HeaderFooter = section.HeadersFooters.Footer
Dim footerPara As Paragraph = footer.AddParagraph()
footerPara.Format.HorizontalAlignment = HorizontalAlignment.Center
textrange = footerPara.AppendText("Copyright © 2021 All Rights Reserved.")
textrange.CharacterFormat.Bold = False
textrange.CharacterFormat.FontSize = 11
'Save to file
document.SaveToFile("output.docx", FileFormat.Docx)
End Sub
End Class
End Namespace

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.