Articles in this section
Category / Section

How to apply a style to bookmark content in a Word document?

7 mins read

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 apply a style to bookmark content in a Word document using C#.

To achieve this, navigate to the desired bookmark in the Word document and extract its content. Then, iterate through the bookmark content and apply a predefined character style to each element. Finally, replace the original bookmark content with the updated, styled content.

Steps to apply a style to bookmark content in a Word document:

  1. Create a new .NET Core console application project.
    Create console application in Visual Studio
  2. Install the Syncfusion.DocIO.Net.Core NuGet package as a reference to your project from NuGet.org.
    Add DocIO NuGet package reference to the project
Note:

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from a 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 a trial message.

  1. Include the following namespaces in the Program.cs file.
    C#
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO; 
  1. Use the following code example to apply a style to bookmark content in a Word document.
    C#
// Declare a variable to hold the custom character style used for formatting bookmark content.
WCharacterStyle style;

// Load the Word document.
using (WordDocument document = new WordDocument(Path.GetFullPath(@"Data/Template.docx")))
{
    // Navigate to the bookmark named "Tiny_Cubes".
    BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document);
    bookmarkNavigator.MoveToBookmark("Tiny_Cubes");
    // Extract the content inside the bookmark as a separate Word document.
    WordDocument bookmarkContent = bookmarkNavigator.GetBookmarkContent().GetAsWordDocument();
    // Retrieve the character style named "TinyCube" from the style collection.
    IStyleCollection styleCollection = document.Styles;
    style = styleCollection.FindByName("TinyCube") as WCharacterStyle;
    // Apply the retrieved style to all elements in the extracted bookmark content.
    IterateDocumentElements(bookmarkContent);
    // Create a WordDocumentPart from the modified bookmark content.
    WordDocumentPart wordDocumentPart = new WordDocumentPart(bookmarkContent);
    // Replace the original bookmark content with the styled content.
    bookmarkNavigator.ReplaceContent(wordDocumentPart);
    // Save the updated document to a new file.
    document.Save(Path.GetFullPath(@"Output/Result.docx"), FormatType.Docx);
}
  1. Use the following code example to iterates all sections, headers, and footers in the given document.
    C#
void IterateDocumentElements(WordDocument document)
{
    foreach (WSection section in document.Sections)
    {
        // Process the main body of the section.
        IterateTextBody(section.Body);
        // Process the header and footer (only OddHeader and OddFooter here).
        WHeadersFooters headersFooters = section.HeadersFooters;
        IterateTextBody(headersFooters.OddHeader);
        IterateTextBody(headersFooters.OddFooter);
    }
}
  1. Use the following code example to iterates all entities within a WTextBody…
    C#
void IterateTextBody(WTextBody textBody)
{
    for (int i = 0; i < textBody.ChildEntities.Count; i++)
    {
        IEntity bodyItemEntity = textBody.ChildEntities[i];
        switch (bodyItemEntity.EntityType)
        {
            case EntityType.Paragraph:
                // Process paragraph items (text, fields, etc.)
                IterateParagraph((bodyItemEntity as WParagraph).Items);
                break;
            case EntityType.Table:
                // Recursively process each cell in the table.
                IterateTable(bodyItemEntity as WTable);
                break;
            case EntityType.BlockContentControl:
                // Recursively process the text body within a block content control.
                IterateTextBody((bodyItemEntity as BlockContentControl).TextBody);
                break;
        }
    }
}
  1. Use the following code example to iterates all rows and cells in a table, processing each cell’s text body.
    C#
void IterateTable(WTable table)
{
    foreach (WTableRow row in table.Rows)
    {
        foreach (WTableCell cell in row.Cells)
        {
            // Each cell is a TextBody; reuse IterateTextBody to process its content.
            IterateTextBody(cell);
        }
    }
}
  1. Use the following code example to iterates all paragraph items and applies the specified style formatting.
    C#
void IterateParagraph(ParagraphItemCollection paraItems)
{
    for (int i = 0; i < paraItems.Count; i++)
    {
        Entity entity = paraItems[i];
        switch (entity.EntityType)
        {
            case EntityType.TextRange:
                // Apply the character style to the text range.
                (entity as WTextRange).ApplyCharacterFormat(style.CharacterFormat);
                break;
            case EntityType.Field:
                // Apply the character style to the field.
                (entity as WField).ApplyCharacterFormat(style.CharacterFormat);
                break;
            case EntityType.TextBox:
                // Recursively process the contents of the textbox.
                IterateTextBody((entity as WTextBox).TextBoxBody);
                break;
            case EntityType.Shape:
                // Recursively process the contents of the shape.
                IterateTextBody((entity as Shape).TextBody);
                break;
            case EntityType.InlineContentControl:
                // Recursively process the paragraph items within the inline content control.
                IterateParagraph((entity as InlineContentControl).ParagraphItems);
                break;
        }
    }
}

You can download a complete working sample to apply a style to bookmark content in a Word document from GitHub.

Output Word document

Take a moment to peruse the documentation where you can find basic Word document processing options along with 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 apply a style to bookmark content in a Word document in a .NET Core Word document.

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 with 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!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied