Need to update Bookmarks content style

Hello,

I have an existing Word document with 3 bookmarks. I would like to apply a different style on each bookmarks content (on each bookmark’s paragraphs!) :

- “BOOKMARK1” : Arial font, size 11pt, bold
- “BOOKMARK2” : Verdana font, size 8pt, italic
- “BOOKMARK3” : Times New Romain font, size 12pt, underline

I’ve try with a DocumentBuilder like this but that doesn’t work :

Document doc = new Document("c:\Sample.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToBookmark("BOOKMARK1");
builder.Font.Name = "Arial";
builder.Font.Size = 10;


doc.Save("c:\out.docx");

Could you help me to do that ? There my “Sample.docx” file attached to this post: )

Thanks so much,

Hi,

Thanks for your inquiry.

Bookmark consists of BoomarkStart and BookmarkEnd nodes. All content between these nodes is bookmark’s content. So if you need to change font formatting of content inside bookmark, you need to change formatting of individual Runs between BookmarkStart and BookmarkEnd nodes. You can easily achieve this using DocumentVisitor:
https://reference.aspose.com/words/net/aspose.words/documentvisitor/

Here is the sample code to achieve what you’re looking for:

Document doc = new Document(@"C:\Temp\Sample.docx");
BookmarkFontChanger fontChanger = new BookmarkFontChanger();
doc.Accept(fontChanger);
doc.Save(@"C:\Temp\out.docx");
public class BookmarkFontChanger: DocumentVisitor
{
    public BookmarkFontChanger()
    {
        whichBookmark = -1;
    }
    public override VisitorAction VisitBookmarkStart(BookmarkStart start)
    {
        if (start.Name.Equals("BOOKMARK1"))
            whichBookmark = 1;
        else if (start.Name.Equals("BOOKMARK2"))
            whichBookmark = 2;
        else if (start.Name.Equals("BOOKMARK3"))
            whichBookmark = 3;
        else
            whichBookmark = -1;
        return VisitorAction.Continue;
    }
    public override VisitorAction VisitBookmarkEnd(BookmarkEnd end)
    {
        whichBookmark = -1;
        return VisitorAction.Continue;
    }
    public override VisitorAction VisitRun(Run run)
    {
        switch (whichBookmark)
        {
            case 1:
                run.Font.Name = "Arial";
                run.Font.Size = 11;
                run.Font.Bold = true;
                break;
            case 2:
                run.Font.Name = "Verdana";
                run.Font.Size = 8;
                run.Font.Italic = true;
                break;
            case 3:
                run.Font.Name = "Times New Romain";
                run.Font.Size = 12;
                run.Font.Underline = Underline.Single;
                break;
            default:
                break;
        }
        return VisitorAction.Continue;
    }
    private int whichBookmark;
}

I hope, this helps.

Best regards,

Nice! Thank you very much :slight_smile: it’s perfect.