Syncfusion; Essential; DocIO is a .NET Word library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can find text and add bookmarks in Word document using C#. You can achieve the requirement by following these steps: Open the template Word document. Add a bookmark to the searched text. Find all bookmarks in the Word document using the FindAllItemsByProperty API. Iterate through the bookmarks and get the content from each bookmark. Steps to find text and add bookmarks in Word document: Create a new .NET Core console application project. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org. Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion® license key in your application to use the components without trail message. Include the following namespaces in Program.cs file C# using Syncfusion.DocIO.DLS; using Syncfusion.DocIO; Use the following code example to find text and add bookmarks in Word document. C# using (FileStream fileStream = new FileStream(Path.GetFullPath(@"Data/Template.docx"), FileMode.Open, FileAccess.ReadWrite)) { using (WordDocument document = new WordDocument(fileStream, FormatType.Automatic)) { // Define texts and corresponding bookmark names var textBookmarkPairs = new Dictionary<string, string> { { "they are considered one of the world's most loved animals.", "bkmk1" }, { "The table below lists the main characteristics the giant panda shares with bears and red pandas.", "bkmk2" }, { "Did you know that the giant panda may actually be a raccoon", "bkmk3" } }; // Add bookmarks to specified texts foreach (var pair in textBookmarkPairs) { AddBookmarkToText(document, pair.Key, pair.Value); } // Retrieve and display bookmark contents List<string> bookmarksContent = GetBookmarkContents(document); foreach (var content in bookmarksContent) { Console.WriteLine("Bookmark content: "); Console.WriteLine(content); } // Save the modified document using (FileStream outputStream = new FileStream(Path.GetFullPath(@"Output/Result.docx"), FileMode.Create, FileAccess.ReadWrite)) { document.Save(outputStream, FormatType.Docx); } } } Use the following code example to adds a bookmark to a specific text in the document. C# private static void AddBookmarkToText(WordDocument document, string searchText, string bookmarkName) { TextSelection textSelection = document.Find(searchText, false, true); if (textSelection != null) { WTextRange textRange = textSelection.GetAsOneRange(); int indexOfText = textRange.OwnerParagraph.Items.IndexOf(textRange); textRange.OwnerParagraph.Items.Insert(indexOfText, new BookmarkStart(document, bookmarkName)); textRange.OwnerParagraph.Items.Insert(indexOfText + 2, new BookmarkEnd(document, bookmarkName)); } } Use the following code example to retrieves all bookmark contents from the document. C# private static List<string> GetBookmarkContents(WordDocument document) { List<string> bookmarkContents = new List<string>(); foreach (Entity entity in document.FindAllItemsByProperty(EntityType.BookmarkStart, null, null)) { if (entity is BookmarkStart bookmarkStart) { var bookmarkNavigator = new BookmarksNavigator(document); bookmarkNavigator.MoveToBookmark(bookmarkStart.Name); WordDocumentPart part = bookmarkNavigator.GetContent(); WordDocument tempDoc = part.GetAsWordDocument(); bookmarkContents.Add(tempDoc.GetText()); tempDoc.Close(); tempDoc.Dispose(); part.Close(); } } return bookmarkContents; } You can download a complete working sample to find text and add bookmarks in Word document from the GitHub. Template Word document Generated result document with bookmark Take a moment to peruse the documentation where you can find basic Word document processing options along with the features like mail merge, merge, split, and compare Word documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples. Conclusion I hope you enjoyed learning about how to find text and add bookmark to get content in ASP.NET Core Word. You can refer to our ASP.NET Core DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core DocIO example to understand how to create and manipulate data. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
Syncfusion® Essential® DocIO is a .NET Word Library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can maintain list format of the source document to destination document after replacing bookmark content using C#. When replacing bookmark content in a Word document using the ReplaceContent method, the list format from the destination document is not applied to the replaced content. Instead, the replaced content retains the formatting from the source document. To maintain the list format from the destination document, you can retrieve the paragraph containing the replaced content after the replacement and apply the appropriate list formatting. Steps to maintain list format of the source document to destination document after replacing bookmark content: Create a new .NET Core console application project. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org. Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering a Syncfusion® license key in your application to use the components without trail message. Include the following namespaces in Program.cs file C# using Syncfusion.DocIO.DLS; using Syncfusion.DocIO; Use the following code example to maintain list format of the source document to destination document after replacing bookmark content. C# using (FileStream destinationStream = new FileStream(Path.GetFullPath("Data/DestinationDocument.docx"), FileMode.Open, FileAccess.Read)) { //Open the destination Word document. using (WordDocument destinationDocument = new WordDocument(destinationStream, FormatType.Docx)) { using (FileStream srcStream = new FileStream(Path.GetFullPath(@"Data/SourceDocument.docx"), FileMode.Open, FileAccess.Read)) { //Open the source Word document. using (WordDocument srcDocument = new WordDocument(srcStream, FormatType.Docx)) { //Replace text "Text one" in the destination document with content from the bookmark "bkmk1" in the source document. ReplaceTextAndMaintainListFormat(destinationDocument, srcDocument, "Text one", "bkmk1"); //Replace text "Text two" in the destination document with content from the bookmark "bkmk2" in the source document. ReplaceTextAndMaintainListFormat(destinationDocument, srcDocument, "Text two", "bkmk2"); //Save the modified destination document to the output stream. using (FileStream output = new FileStream(Path.GetFullPath("Output/Output.docx"), FileMode.Create, FileAccess.Write)) { destinationDocument.Save(output, FormatType.Docx); } } } } } Use the following helper method to replace text in a Word document with bookmark content from another document. C# /// <summary> /// Replaces specific text in a Word document with bookmarked content from another document, maintaining formatting. /// </summary> private static void ReplaceTextAndMaintainListFormat(WordDocument destinationDocument, WordDocument sourceDocument, string tokenToFind, string textBookmark) { string bookmarkRef = textBookmark + "_bm"; // Find the text in the destination document where the bookmark start needs to be inserted. TextSelection start = destinationDocument.Find(tokenToFind, true, true); if (start != null) { // Get the selected text range and its parent paragraph. WTextRange startText = start.GetAsOneRange(); WParagraph startParagraph = startText.OwnerParagraph; // Get the index of the selected text range in the paragraph. int index = startParagraph.Items.IndexOf(startText); // Remove the selected text at the identified index. startParagraph.Items.Remove(startText); // Create a BookmarkStart with a unique reference and insert it at the same index. BookmarkStart bookmarkStart = new BookmarkStart(destinationDocument, bookmarkRef); startParagraph.Items.Insert(index, bookmarkStart); // Append a BookmarkEnd with the same reference to mark the bookmark’s end. startParagraph.AppendBookmarkEnd(bookmarkRef); // Check if the specified bookmark exists in the source document. if (sourceDocument.Bookmarks.FindByName(textBookmark) != null) { // Move the navigator to the bookmark in the source document. BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(sourceDocument); bookmarksNavigator.MoveToBookmark(textBookmark); // Extract the content within the bookmark. WordDocumentPart wordDocumentPart = bookmarksNavigator.GetContent(); // Move the navigator to the newly created bookmark in the destination document. bookmarksNavigator = new BookmarksNavigator(destinationDocument); bookmarksNavigator.MoveToBookmark(bookmarkRef); // Get the paragraph containing the bookmark start in the destination document. WParagraph destinationPara = bookmarksNavigator.CurrentBookmark.BookmarkStart.OwnerParagraph; // Store the list style, first-line indent, and left indent of the paragraph. string listStyleName = destinationPara.ListFormat.CustomStyleName; float firstLineIndent = destinationPara.ParagraphFormat.FirstLineIndent; float leftIndent = destinationPara.ParagraphFormat.LeftIndent; // Replace the bookmark content with the extracted content from the source document. bookmarksNavigator.ReplaceContent(wordDocumentPart); // Reapply the original list style and indent settings to the paragraph. destinationPara.ListFormat.ApplyStyle(listStyleName); destinationPara.ParagraphFormat.FirstLineIndent = firstLineIndent; destinationPara.ParagraphFormat.LeftIndent = leftIndent; } else { // If the bookmark is not found, replace the content with an empty string. BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(destinationDocument); bookmarksNavigator.MoveToBookmark(bookmarkRef); bookmarksNavigator.ReplaceBookmarkContent(string.Empty, true); } } } You can download a complete working sample to maintain list format of the source document to destination document after replacing bookmark content from the GitHub. The input documents are as follows. By executing the program, you will get the Word document as follows. Take a moment to peruse the documentation where you can find basic Word document processing options along with the features like mail merge, merge, split, and compare Word documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples. Conclusion I hope you enjoyed learning about how to maintain list format of the source document to destination document after replacing bookmark content. You can refer to our ASP.NET Core DocIO feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our ASP.NET Core DocIO example to understand how to create and manipulate data. For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls. If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
Syncfusion® Essential® DocIO is a .NET Core Word library used to create, read, and edit Word documents programmatically without Microsoft Word or Interop dependencies. Using this library, you can get the section number of the particular bookmark in C#. Steps to get the section number of the particular bookmark using C# Create a new C# .NET Core console application project. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your .NET Core applications from NuGet.org. Include the following namespace in the Program.cs file: C# using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; Use the following code example to get the section number of the particular bookmark in C#. C# using (FileStream fileStreamPath = new FileStream(Path.GetFullPath(@"../../../Input.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { //Open an existing Word document. using (WordDocument document = new WordDocument(fileStreamPath, FormatType.Automatic)) { // Get the bookmark instance by using FindByName method of BookmarkCollection with bookmark name Bookmark bookmark = document.Bookmarks.FindByName("BOOKMARK2"); if (bookmark != null) { // Get the owner section of bookmark. WSection section = GetOwnerEntity(bookmark.BookmarkStart) as WSection; if (section != null) { // Get the index value of section. int sectionIndex = document.ChildEntities.IndexOf(section); int sectionNumber = sectionIndex + 1; Console.WriteLine("This bookmark would be in section " + sectionNumber); Console.ReadKey(); } } } } Helper method C# /// <summary> /// Get the Entity owner. /// </summary> private static Entity GetOwnerEntity(BookmarkStart bookmarkStart) { Entity baseEntity = bookmarkStart.Owner; while (!(baseEntity is WSection)) { if (baseEntity is null) return baseEntity; baseEntity = baseEntity.Owner; } return baseEntity; } A complete working sample to get the section number of the particular bookmark in C# can be downloaded from GitHub. Input Word document as follows. By executing the program, you will get the output document as follows. Take a moment to peruse the documentation where you can find basic Word document processing options along with the features like mail merge, merge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples. Explore more about the rich set of Syncfusion® Word Framework features. See Also: How do I insert hidden bookmarks to the document? How to replace text within bookmark content in Word document? Is it possible to insert table in BookMark Content? How to replace the content between two different existing bookmarks in a word document Conclusion I hope you enjoyed learning about how to get the section number of the particular bookmark in C#. You can refer to our ASP.NET Core DocIO’s feature tour page to know about its other groundbreaking feature representations. You can also explore our ASP.NET Core DocIO documentation to understand how to present and manipulate data. For current customers, you can check out our ASP.NET Core components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our ASP.NET Core DocIO and other ASP.NET Core components. If you have any queries or require clarifications, please let us know in the comment section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
Syncfusion® Essential® DocIO is a .NET Core Word library used to create, read, and edit Word documents programmatically without Microsoft Word or Interop dependencies. Using this library, you can insert bookmark for a particular text in a paragraph in the Word document in C#. Steps to insert bookmark for a text in a paragraph in the Word document: Create a new C# .NET Core console application project. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your .NET Core applications from NuGet.org. Include the following namespace in the Program.cs file: C# using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; Use the following code example to insert bookmark for a text in a paragraph in the Word document: C# //Open the file as a stream. using (FileStream inputStream = new FileStream(Path.GetFullPath(@"../../../Input.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { //Load the file stream into a Word document. using (WordDocument document = new WordDocument(inputStream, FormatType.Docx)) { //Access paragraph in a Word document. WParagraph paragraph = document.Sections[0].Paragraphs[3] as WParagraph; //Create bookmarkstart and bookmarkend instance. BookmarkStart bookmarkStart = new BookmarkStart(document, "Northwind"); BookmarkEnd bookmarkEnd = new BookmarkEnd(document, "Northwind"); //Add bookmarkstart at index zero. paragraph.Items.Insert(0, bookmarkStart); //Add bookmarkend at index 2. paragraph.Items.Insert(2, bookmarkEnd); //Create a file stream. using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"../../../Sample.docx"), FileMode.Create, FileAccess.ReadWrite)) { //Save the Word document to the file stream. document.Save(outputFileStream, FormatType.Docx); } } } A complete working sample to insert bookmark for a particular text in a paragraph in the Word document in C# can be downloaded from GitHub. By executing the program, you will get the Output document as follows. Take a moment to peruse the documentation, where you can find basic Word document processing options along with the features like mail merge, merge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples. Explore more about the rich set of Syncfusion® Word Framework features. See Also: How to replace the content between two different existing bookmarks in a word document How to insert hidden bookmarks to the document How to insert nested bookmarks to the document How to get the bookmarks present in the document How to add a table in a bookmark location Note:Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion® license key in your application to use the components without trail message.
Syncfusion® Essential® DocIO is a .NET Core Word library used to create, read, and edit Word documents programmatically without Microsoft Word or Interop dependencies. Using this library, you can replace a particular text within bookmark in the Word document in C#. Steps to replace a text within bookmark content in the Word document: Create a new C# .NET Core console application project. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your .NET Core applications from NuGet.org. Include the following namespace in the Program.cs file: C# using Syncfusion.DocIO; using Syncfusion.DocIO.DLS; Use the following code example to replace a text within bookmark content in the Word document. C# //Open the file as a stream. using (FileStream inputStream = new FileStream(Path.GetFullPath(@"../../../Input.docx"), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { //Load the file stream into a Word document. using (WordDocument document = new WordDocument(inputStream, FormatType.Docx)) { //Replace a text within the bookmark. ReplaceBookmarkText(document, "Description", "Price", "Amount"); ReplaceBookmarkText(document, "Address", "290", "two hundred and ninety"); //Create a file stream. using (FileStream outputFileStream = new FileStream(Path.GetFullPath(@"../../../Sample.docx"), FileMode.Create, FileAccess.ReadWrite)) { //Save the Word document to the file stream. document.Save(outputFileStream, FormatType.Docx); } } } The following code example shows ReplaceBookmarkText method which is used to replace a text within a bookmark content. C# public static void ReplaceBookmarkText(WordDocument document, string bookmarkName, string textToFind, string textToReplace) { //Check whether the bookmark name is valid. if (string.IsNullOrEmpty(bookmarkName) || document.Bookmarks.FindByName(bookmarkName) == null) return; //Move to the virtual cursor before the bookmark end location of the bookmark. BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); bookmarksNavigator.MoveToBookmark(bookmarkName); //Replace the bookmark content with new text. TextBodyPart textBodyPart = bookmarksNavigator.GetBookmarkContent(); //Get paragraph from the textBody part. foreach (TextBodyItem item in textBodyPart.BodyItems) { IterateTextBody(item, textToFind, textToReplace); } //Replace the bookmark content with text body part. bookmarksNavigator.ReplaceBookmarkContent(textBodyPart); } The following code example shows IterateTextBody method which is used to iterate text body elements. C# public static void IterateTextBody(TextBodyItem item, string textToFind, string textToReplace) { switch (item.EntityType) { case EntityType.Paragraph: WParagraph paragraph = (WParagraph)item; //Replace a text in the bookmark content. paragraph.Replace(new System.Text.RegularExpressions.Regex(textToFind), textToReplace); break; case EntityType.Table: WTable table = (WTable)item; foreach (WTableRow row in table.Rows) { foreach (WTableCell cell in row.Cells) { foreach (TextBodyItem bodyItem in cell.ChildEntities) { IterateTextBody(bodyItem, textToFind, textToReplace); } } } break; case EntityType.BlockContentControl: WTextBody body = (item as IBlockContentControl).TextBody; foreach (TextBodyItem bodyitem in body.ChildEntities) IterateTextBody(bodyitem, textToFind, textToReplace); break; } } A complete working sample to replace a text within a bookmark content in the Word document in C# can be downloaded from GitHub. By executing the program, you will get the Output document as follows. Take a moment to peruse the documentation, where you can find basic Word document processing options along with the features like mail merge, merge and split documents, find and replace text in the Word document, protect the Word documents, and most importantly, the PDF and Image conversions with code examples. Explore more about the rich set of Syncfusion® Word Framework features. See Also: How to replace the particular text with hyperlink in Word document How to find the empty paragraphs in the Word document using DocIO How to replace text in a Word document with HTML How to find and replace text inside table in Word document How to find and replace text in headers and footers of Word document How to find and replace placeholder with page break in Word document How to find and replace text with content control in Word document? How to find and replace line break in Word document as paragraph mark? Note:Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion® license key in your application to use the components without trail message.
The Syncfusion Essential® Winforms PDPDF is a feature-rich and high-performance .NET PDF library that is used to create, read, and edit PDF documents programmatically without Adobe dependencies. Using this library, you can split the PDF document based on each bookmarks using C# and VB.NET. Steps to split the PDF document based on each bookmarks using C# programmatically 1. Create a new C# console application project. 2. Install the Syncfusion.PDF.WinForms NuGet packages as a reference to your .NET Framework application from NuGet.org. 3. Include the following namespaces in the Program.cs file. C# using Syncfusion.Pdf; using Syncfusion.Pdf.Parsing; using Syncfusion.Pdf.Interactive; VB.NET Imports Syncfusion.Pdf Imports Syncfusion.Pdf.Parsing Imports Syncfusion.Pdf.Interactive 4. The following code example shows how to split the PDF document based on each bookmarks using C#. C# //Load the PDF document PdfLoadedDocument lDoc = new PdfLoadedDocument(@"../../Data/BookmarksPDF.pdf"); Dictionary<PdfPageBase, int> pages = new Dictionary<PdfPageBase, int>(); //Maintain collection for page and its index for (int i = 0; i < lDoc.Pages.Count; i++) { PdfPageBase page = lDoc.Pages[i] as PdfPageBase; pages.Add(page, i); } //Get all the bookmarks PdfBookmarkBase bookmarks = lDoc.Bookmarks; //Iterate throws all the bookmarks. for (int i = 0; i < bookmarks.Count; i++) { //Get the bookmark. PdfBookmark bk = bookmarks[i]; TotalBookmarks.Add(bk); Getbookmark(bk); } //Create a dictionary with a bookmark and split up page range List<SplitRange> splitRanges = new List<SplitRange>(); GetPageofBookmarks(lDoc, splitRanges, pages); //Spit the PDF based on range of bookmark for (int i = 0; i < splitRanges.Count; i++) { int startIndex = splitRanges[i].startIndex; int endIndex = splitRanges[i].endIndex; for (int j = 0; j < splitRanges.Count; j++) { if (splitRanges[j].startIndex > startIndex && splitRanges[j].endIndex <= endIndex) { splitRanges[i].endIndex = splitRanges[j].startIndex - 1; ; } } //Create a new PDF document PdfDocument document = new PdfDocument(); //Import the pages to the new PDF document document.ImportPageRange(lDoc, startIndex, endIndex); //Save the document in a specified folder document.Save(DataPathOutput + "Output_" + i + ".pdf"); //Close the document document.Close(true); } //Close the document lDoc.Close(true); splitRanges.Clear(); pages.Clear(); //Opens the folder where the output documents are saved System.Diagnostics.Process.Start(DataPathOutput); //Split bookmark with pages private static List<SplitRange> GetPageofBookmarks(PdfLoadedDocument lDoc, List<SplitRange> splitRanges, Dictionary<PdfPageBase, int> pages) { for (int i = 0; i < TotalBookmarks.Count; i++) { if (TotalBookmarks[i].Destination != null) { PdfPageBase page = TotalBookmarks[i].Destination.Page; if (pages.ContainsKey(page)) { int startIndex = pages[page]; int endIndex = startIndex; if (i + 1 < TotalBookmarks.Count && TotalBookmarks[i + 1].Destination != null) { page = TotalBookmarks[i + 1].Destination.Page; if (pages[page] - 1 > startIndex) endIndex = pages[page] - 1; } else { for (int j = 0; j < splitRanges.Count; j++) { int checkStartIndex = splitRanges[j].startIndex; int checkEndIndex = splitRanges[j].endIndex; if (endIndex > checkStartIndex && endIndex < checkEndIndex) { endIndex = checkEndIndex; break; } else endIndex = lDoc.Pages.Count - 1; } } splitRanges.Add(new SplitRange() { bookmarkTitle = TotalBookmarks[i].Title, startIndex = startIndex, endIndex = endIndex }); } } } return splitRanges; } //Get all level of bookmarks public static void Getbookmark(PdfBookmark bookmark) { for (int i = 0; i < bookmark.Count; i++) { PdfBookmark bk = bookmark[i]; TotalBookmarks.Add(bk); Getbookmark(bk); } } VB.NET 'Load the PDF document Dim lDoc As PdfLoadedDocument = New PdfLoadedDocument("../../Data/BookmarksPDF.pdf") Dim pages As Dictionary(Of PdfPageBase, Integer) = New Dictionary(Of PdfPageBase, Integer)() 'Maintain collection for page and its index For i As Integer = 0 To lDoc.Pages.Count - 1 Dim page As PdfPageBase = TryCast(lDoc.Pages(i), PdfPageBase) pages.Add(page, i) Next 'Get all the bookmarks Dim bookmarks As PdfBookmarkBase = lDoc.Bookmarks 'Iterate throw all the bookmarks. For i As Integer = 0 To bookmarks.Count - 1 'Get the bookmark. Dim bk As PdfBookmark = bookmarks(i) TotalBookmarks.Add(bk) Getbookmark(bk) Next 'Create a dictionary with a bookmark and split up page range Dim splitRanges As List(Of SplitRange) = New List(Of SplitRange)() GetPageofBookmarks(lDoc, splitRanges, pages) 'Spit the PDF based on range of bookmark For i As Integer = 0 To splitRanges.Count - 1 Dim startIndex As Integer = splitRanges(i).startIndex Dim endIndex As Integer = splitRanges(i).endIndex For j As Integer = 0 To splitRanges.Count - 1 If splitRanges(j).startIndex > startIndex AndAlso splitRanges(j).endIndex <= endIndex Then splitRanges(i).endIndex = splitRanges(j).startIndex - 1 End If Next 'Create a new PDF document Dim document As PdfDocument = New PdfDocument() 'Import the pages to the new PDF document document.ImportPageRange(lDoc, startIndex, endIndex) 'Save the document in a specified folder document.Save(DataPathOutput & "Output_" & i & ".pdf") 'Close the document document.Close(True) Next 'Close the document lDoc.Close(True) splitRanges.Clear() pages.Clear() 'Opens the folder where the output documents are saved System.Diagnostics.Process.Start(DataPathOutput) 'Split bookmark with pages Private Function GetPageofBookmarks(ByVal lDoc As PdfLoadedDocument, ByVal splitRanges As List(Of SplitRange), ByVal pages As Dictionary(Of PdfPageBase, Integer)) As List(Of SplitRange) For i As Integer = 0 To TotalBookmarks.Count - 1 If TotalBookmarks(i).Destination IsNot Nothing Then Dim page As PdfPageBase = TotalBookmarks(i).Destination.Page If pages.ContainsKey(page) Then Dim startIndex As Integer = pages(page) Dim endIndex As Integer = startIndex If i + 1 < TotalBookmarks.Count AndAlso TotalBookmarks(i + 1).Destination IsNot Nothing Then page = TotalBookmarks(i + 1).Destination.Page If pages(page) - 1 > startIndex Then endIndex = pages(page) - 1 Else For j As Integer = 0 To splitRanges.Count - 1 Dim checkStartIndex As Integer = splitRanges(j).startIndex Dim checkEndIndex As Integer = splitRanges(j).endIndex If endIndex > checkStartIndex AndAlso endIndex < checkEndIndex Then endIndex = checkEndIndex Exit For Else endIndex = lDoc.Pages.Count - 1 End If Next End If splitRanges.Add(New SplitRange() With { .bookmarkTitle = TotalBookmarks(i).Title, .startIndex = startIndex, .endIndex = endIndex }) End If End If Next Return splitRanges End Function 'Get all level of bookmarks Public Sub Getbookmark(ByVal bookmark As PdfBookmark) For i As Integer = 0 To bookmark.Count - 1 Dim bk As PdfBookmark = bookmark(i) TotalBookmarks.Add(bk) Getbookmark(bk) Next End Sub By executing the program, you will get the PDF document as follows. A complete working sample can be downloaded from PdfBookmarkSplit.zip. Take a moment to peruse the documentation. You can find other options like adding, Inserting, removing, and modifying bookmarks in an existing PDF document and features like named destination, interactive annotations, PDF form filling, and insert a hyperlink to PDF with code examples. Refer to here to explore a rich set of Syncfusion Essential® PDF features. An online sample link to Add Bookmarks. Note:Starting with v16.2.0.x, if you reference Syncfusion® assemblies from the trial setup or NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without trail message. See Also: https://help.syncfusion.com/file-formats/pdf/working-with-bookmarks https://support.syncfusion.com/kb/article/8228/how-to-add-bookmarks-in-a-pdf-using-c-and-vb-net https://support.syncfusion.com/kb/article/8368/how-to-get-bookmarks-from-a-pdf-using-c-and-vb-net https://support.syncfusion.com/kb/article/8574/how-to-create-hierarchical-bookmarks-in-a-pdf-file-using-c-and-vbnetConclusionI hope you enjoyed learning about how to split WinForms PDF document based on each level of bookmarks.You can refer to our Winforms PDF feature tour page to know about its other groundbreaking feature representations. You can also explore our documentation to understand how to create and manipulate data.For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!
Syncfusion Essential® PDF is a .NET PDF library used to create, read, and edit PDF documents. Using this library, you can display both pages and bookmarks in PDF documents. Steps to display both pages and bookmarks in the PDF documents programmatically Create a new C# console application project. Install the Syncfusion.Pdf.WinForms NuGet package as a reference to your .NET Framework application from the NuGet.org. Include the following namespaces in the Program.cs file. C# using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using Syncfusion.Pdf.Interactive; using System.Drawing; VB.NET Imports Syncfusion.Pdf Imports Syncfusion.Pdf.Graphics Imports Syncfusion.Pdf.Interactive Imports System.Drawing Use the following code snippet to display both page and bookmarks in the PDF document. C# //Creates a new document PdfDocument document = new PdfDocument(); //Set to open bookmarks document.ViewerPreferences.PageMode = PdfPageMode.UseOutlines; //Add a page PdfPage page = document.Pages.Add(); //Create parent bookmark PdfBookmark bookmark = document.Bookmarks.Add("Page 1"); bookmark.Destination = new PdfDestination(page); bookmark.Destination.Location = new PointF(20, 20); //Add the child bookmark PdfBookmark childBookmark = bookmark.Insert(0, "Heading 1"); childBookmark.Destination = new PdfDestination(page); childBookmark.Destination.Location = new PointF(0, 300); childBookmark.Destination.Zoom = 2F; //Draw string page.Graphics.DrawString("Hello World", new PdfStandardFont(PdfFontFamily.Helvetica, 20), PdfBrushes.Black, new PointF(0, 0)); //Sets the text style and color bookmark.TextStyle = PdfTextStyle.Bold; bookmark.Color = System.Drawing.Color.Red; //Saves and closes the PDF document document.Save("Output.pdf"); document.Close(true); //This will open the PDF file so, the result will be seen in the default PDF viewer System.Diagnostics.Process.Start("Output.pdf"); VB.NET 'Creates a New document Dim document As PdfDocument = New PdfDocument() 'Set to open bookmarks document.ViewerPreferences.PageMode = PdfPageMode.UseOutlines 'Add a page Dim page As PdfPage = document.Pages.Add() 'Create parent bookmark Dim bookmark As PdfBookmark = document.Bookmarks.Add("Page 1") bookmark.Destination = New PdfDestination(page) bookmark.Destination.Location = New PointF(20, 20) 'Adds the child bookmark Dim childBookmark As PdfBookmark = bookmark.Insert(0, "Heading 1") childBookmark.Destination = New PdfDestination(page) childBookmark.Destination.Location = New PointF(0, 300) childBookmark.Destination.Zoom = 2.0F 'Draw String page.Graphics.DrawString("Hello World", New PdfStandardFont(PdfFontFamily.Helvetica, 20), PdfBrushes.Black, New PointF(0, 0)) 'Sets the text style And color bookmark.TextStyle = PdfTextStyle.Bold bookmark.Color = System.Drawing.Color.Red 'Saves And closes the PDF document document.Save("Output.pdf") document.Close(True) 'This will open the PDF file so, the result will be seen in the default PDF viewer System.Diagnostics.Process.Start("Output.pdf") A complete working sample can be downloaded from BookmarkSample.zip. By executing the program, you will get the PDF document as follows, Take a moment to peruse the documentation, where you can find other options like adding child bookmarks, inserting bookmarks, removing, and modifying bookmarks in the PDF document with code example. Refer here to explore the rich set of Syncfusion Essential® PDF features. Note:Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without trail message. See Also: Add bookmarks in PDF document
Syncfusion Essential PDF is a .NET PDF library used to create, read, and edit PDF documents. Using this library, you can get the page number from a PDF bookmark using C# and VB.NET. Steps to get the page number from a PDF bookmark programmatically: Create a new C# console application project. Install the Syncfusion.Pdf.WinForms NuGet package as reference to your .NET Framework application from NuGet.org. Use the following namespaces in the Program.cs file. C# using Syncfusion.Pdf; using Syncfusion.Pdf.Interactive; using Syncfusion.Pdf.Parsing; VB.NET Imports Syncfusion.Pdf Imports Syncfusion.Pdf.Parsing Imports Syncfusion.Pdf.Interactive Use the following code snippet to get the page number from a PDF bookmark. C# //Load the PDF document PdfLoadedDocument document = new PdfLoadedDocument("Input.pdf"); //Create the dictionary Dictionary<PdfPageBase, int> pages = new Dictionary<PdfPageBase, int>(); //Iterates through the pages for (int i = 0; i < document.Pages.Count; i++) { PdfPageBase page = document.Pages[i] as PdfPageBase; //Add the page and index to dictionary pages.Add(page, i); } //Get all the bookmarks PdfBookmarkBase bookmarks = document.Bookmarks; //Iterates through bookmarks foreach (PdfBookmark bookmark in bookmarks) { //Get the bookmark destination page PdfPageBase page = bookmark.Destination.Page; if (pages.ContainsKey(page)) { //Get the page number of the bookmark int index = pages[page]; Console.WriteLine("Bookmark Name: "+bookmark.Title + ", Page no: " + (index + 1)); } } //Close the document document.Close(true); Console.ReadLine(); VB.NET 'Load the PDF document Dim document As PdfLoadedDocument = New PdfLoadedDocument("Input.pdf") 'Create the dictionary Dim pages As Dictionary(Of PdfPageBase, Integer) = New Dictionary(Of PdfPageBase, Integer)() 'Iterates through the pages For i As Integer = 0 To document.Pages.Count - 1 Dim page As PdfPageBase = TryCast(document.Pages(i), PdfPageBase) 'Add the page and index to dictionary pages.Add(page, i) Next 'Get all bookmarks Dim bookmarks As PdfBookmarkBase = document.Bookmarks 'Iterates through bookmarks For Each bookmark As PdfBookmark In bookmarks 'Get the bookmark destination page Dim page As PdfPageBase = bookmark.Destination.Page If pages.ContainsKey(page) Then Dim index As Integer = pages(page) Console.WriteLine("Bookmark Name: " & bookmark.Title + ", Page no: " & (index + 1)) End If Next 'Close the document document.Close(True) Console.ReadLine() You can download the working sample from PdfBookmarkSample.zip. By executing the program, you will get the console window as follows. Take a moment to peruse the documentation, where you can find other options like adding, inserting, removing, and modifying bookmarks in an existing PDF document and features like named destination and Document Link Annotation with code examples. Refer here to explore the rich set of Syncfusion Essential PDF features. Note:Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.