Bookmark

Bookmark (8)

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#]
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]
Dim doc As Document = New Document()
doc.LoadFromFile("C:\Users\Administrator\Desktop\employee.docx")
Dim table As Table = New Table(doc, True)
Dim dt As DataTable = 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 BookmarksNavigator = New BookmarksNavigator(doc)
navigator.MoveToBookmark("bookmark_employee")
Dim part As TextBodyPart = New TextBodyPart(doc)
part.BodyItems.Add(table)
navigator.ReplaceBookmarkContent(part)
doc.SaveToFile("output.docx", FileFormat.Docx2013)
Wednesday, 03 January 2018 08:44

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

Written by support iceblue

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#]
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]
Document doc = New Document()
doc.LoadFromFile("Bookmark.docx")
 
Dim navigator As BookmarksNavigator = New BookmarksNavigator(doc)
navigator.MoveToBookmark("bookmark_1")
Dim textBodyPart As TextBodyPart = navigator.GetBookmarkContent()


Dim text As String = Nothing
Dim item As var
For Each item In textBodyPart.BodyItems
    If TypeOf item Is Paragraph Then
        Dim childObject As var
        For Each childObject in(item as Paragraph).ChildObjects
            If TypeOf childObject Is TextRange Then
                text += (childObject as TextRange).Text
            End If
        Next
    End If
Next
Console.WriteLine(text)

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:

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

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:

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

        }

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#]
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");

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#]
static void Main(string[] args)
{
 Document document = new Document();
 Section section = document.AddSection();

 //create bookmarks
 Paragraph p1 = section.AddParagraph();
 p1.AppendBookmarkStart("bookmark1");
 p1.AppendHTML("<p><font color='blue'>This para is also Generated by Decoding HTML Code</font></p>");
 p1.AppendBookmarkEnd("bookmark1");

 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");
 document.SaveToFile("BeforeReplace.doc");

 //create a temp section to contain multiple paragraph.
 Section tempSection = document.AddSection();
 String html
 = "<p>This Bookmark has been <font color=\"#ff0000\">Edited</font></p>";
 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");
}
Thursday, 29 November 2012 02:49

Remove Bookmark in C#, VB.NET

Written by support iceblue

Word bookmark is convenient for users to fix location of specified text, sentence or paragraph. The bookmark can be inserted any location of document. Also, it can be named or deleted. The following screenshot presents result document with bookmark.

Remove Word Bookmark

Spire.Doc for .NET, the professional .NET Word component to manipulate Word document, enables users to remove Word bookmark by using C#, VB.NET. Invoke doc.Bookmarks.RemoveAt(int index) method to remove bookmarks. Download and install Spire.Doc for .NET. Then use the following code to remove:

Remove Word Bookmark

[C#]
using Spire.Doc;

namespace Removing
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load Document
            Document doc = new Document();
            doc.LoadFromFile(@"E:\Work\Documents\WordDocuments\Blues Introduction.docx");

            //Remove Bookmark
            doc.Bookmarks.RemoveAt(0);

            //Save and Launch
            doc.SaveToFile("Remove Bookmark.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Remove Bookmark.docx");
        }
    }
}
[VB.NET]
Imports Spire.Doc

Namespace Removing
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim doc As New Document()
            doc.LoadFromFile("E:\Work\Documents\WordDocuments\Blues Introduction.docx")

            'Remove Bookmark
            doc.Bookmarks.RemoveAt(0)

            'Save and Launch
            doc.SaveToFile("Remove Bookmark.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("Remove Bookmark.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, a professional Word component, enables developers/programmers to operate Word document, for example, generating, opening, saving and modifying on .NET, WPF and Silverlight applications

Tuesday, 28 December 2010 02:25

Insert Word Bookmark in C#, VB.NET

Written by Administrator

Word bookmark is convenient for users to go to specified location and modify contents of bookmark range in a document. Solution in this guide introduces how to insert bookmark in existing Word document in C# and VB.NET via Spire.Doc for .NET. In this example, the bookmark range is from the end of the fourth paragraph to the end of the fifth paragraph. The following screenshot presents effect after Work bookmark inserting.

Insert Word Bookmark

Spire.Doc for .NET, a professional .NET Word component, provides two methods to insert Word bookmark, Paragraph.AppendBookmarkStart and Paragraph.AppendBookmarkEnd with parameter string name. The former method is used to append start of the bookmark with specified name into paragraph, while the later to append end of bookmark. Download and install Spire.Doc for .NET and follow the code to insert Word bookmark.

[C#]
using System;
using Spire.Doc;
using Spire.Doc.Documents;

namespace WordBookmark
{
    class Bookmark
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@"E:\Work\Document\.NET Framework.docx");

            //Insert Bookmark
            Section section = document.Sections[0];
            section.Paragraphs[3].AppendBookmarkStart(".NETFramework");
            section.Paragraphs[4].AppendBookmarkEnd(".NETFramework");

            //Save and Launch 
            document.SaveToFile("Bookmark.docx", FileFormat.Docx);
            System.Diagnostics.Process.Start("Bookmark.docx");
        }
    }
}
[VB.NET]
Imports System
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordBookmark
    Friend Class Bookmark
        Shared Sub Main(ByVal args() As String)
            'Load Document
            Dim document As New Document()
            document.LoadFromFile("E:\Work\Document\.NET Framework.docx")

            'Insert Bookmark
            Dim section As Section = document.Sections(0)
            section.Paragraphs(3).AppendBookmarkStart(".NETFramework")
            section.Paragraphs(4).AppendBookmarkEnd(".NETFramework")

            'Save and Launch 
            document.SaveToFile("Bookmark.docx", FileFormat.Docx)
            System.Diagnostics.Process.Start("Bookmark.docx")
        End Sub
    End Class
End Namespace

Spire.Doc, an easy-to-use component to operate Word document, allows developers to fast generate, write, edit and save Word (Word 97-2003, Word 2007, Word 2010) in C# and VB.NET for .NET, Silverlight and WPF.