Replace Bookmark with a Table in Word Documents in C#, VB.NET
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:
Full Code:
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"); } } }
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
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:
Full Code:
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); } } }
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
Set the color for different levels bookmark in word documents
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:
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; } } } }
How to insert an image at bookmark in word documents
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:
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); } } }
How to preserve bookmarks in DOCX to PDF conversion
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:
Full codes:
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"); } } }
Edit/Replace the Content of Word Bookmark with HTML Code
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:
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.
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.
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.
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.
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:
Preview the effect screenshot:
Here comes to the full code:
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"); } } }
Remove Bookmark in C#, VB.NET
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.
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:
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"); } } }
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
C#/VB.NET: Insert a Bookmark in Word
When dealing with a lengthy Word document, inserting bookmarks with different names is a convenient way to mark places in the document. Once the bookmarks are inserted, you can quickly jump to the specified places without scrolling through page after page. In this article, you will learn how to insert a bookmark into an existing Word document 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.
PM> Install-Package Spire.Doc
Insert a Bookmark into an Existing Word Document
Spire.Doc for .NET provides the Paragraph.AppendBookmarkStart(string name) and Paragraph.AppendBookmarkEnd(string name) methods to insert a bookmark with specified name into the specified paragraphs in a Word document. The detailed steps are as follows.
- Create a Document instance.
- Load a sample Word document using Document.LoadFromFile() method.
- Get the first section of the Word Document using Document.Sections[] property.
- Get a specified paragraph of the section using Section.Paragraphs[] property.
- Append the start of the bookmark with specified name to the specified paragraph using Paragraph.AppendBookmarkStart(string name) method.
- Append the end of the bookmark with specified name to the specified paragraph using Paragraph.AppendBookmarkEnd(string name) method.
- Save the document to another file using Document. SaveToFile() method.
- C#
- VB.NET
using Spire.Doc; namespace WordBookmark { class Bookmark { static void Main(string[] args) { //Create a Document instance Document document = new Document(); //Load a sample Word document document.LoadFromFile(@"C:\Users\Administrator\Desktop\test.docx"); //Get the first section Section section = document.Sections[0]; //Insert a bookmark with specified name into the specified paragraphs section.Paragraphs[9].AppendBookmarkStart("SecurityTerm"); section.Paragraphs[11].AppendBookmarkEnd("SecurityTerm"); //Save the document to file document.SaveToFile("Bookmark.docx", FileFormat.Docx); } } }
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.