How to Convert Specific Text to Content Control using .NET

Hello,

We have a requirement to replace the text in word document with SDT control with sdt.type = “Plain Text”.

Using this piece of code to replace

Document doc = new Document(file);

FindReplaceOptions options = new FindReplaceOptions();
options.ReplacingCallback = new FindAndInsertTag("TagName", doc);

doc.Range.Replace("MatchString", string.Empty, options);

Following is the class FindAndInsertTag

public class FindAndInsertTag : IReplacingCallback
{
    String TagName;
    Document document;
    public FindAndInsertTag(string name, Document doc)
    {
        TagName = name;
        document = doc;
    }
    
    ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
    {
        DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
        builder.MoveTo(e.MatchNode);
        StructuredDocumentTag sdt = new StructuredDocumentTag((Document)e.MatchNode.Document, SdtType.PlainText, MarkupLevel.Inline);
        sdt.Title = TagName;
        sdt.Tag = TagName;
        builder.InsertNode(sdt);

        return ReplaceAction.Replace;
    }
}

After replacing the text disappear but we are not able to see the content control added.

How can we replace the text with Sdt control of type plain text ?

Thanks in Advance

@skarlsen

We have tested the scenario using the latest version of Aspose.Words for .NET 21.4 and have not found the shared issue. So, please use Aspose.Words for .NET 21.4. Please check the attached document. 21.4.zip (11.8 KB)

You can add text to content control using following code snippet.

ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)
{
    DocumentBuilder builder = new DocumentBuilder((Document)e.MatchNode.Document);
    builder.MoveTo(e.MatchNode);
    StructuredDocumentTag sdt = new StructuredDocumentTag((Document)e.MatchNode.Document, SdtType.PlainText, MarkupLevel.Inline);
    sdt.Title = TagName;
    sdt.Tag = TagName;
    sdt.RemoveAllChildren();
    sdt.AppendChild(new Run(e.MatchNode.Document, "Text is replaced with SDT"));
    builder.InsertNode(sdt);

    return ReplaceAction.Replace;
}