Dynamically Inserting Content Controls in a Paragraph

Is there a way to replace text inside a paragraph with a content control? i.e. in the code below Replace_With_Checkbox would be replaced with an actual checkbox control and Replace_With_Date_Picker would be replaced with a date picker control:

var doc = new Document();
var builder = new DocumentBuilder(doc);

builder.InsertHtml(“

Replace_With_Checkbox and Replace_With_Date_Picker

”);

The HTML comes from another system so I need to dynamically replace the controls by the regular expression.

@robschenkel,

You can meet this requirement by using the following code:

Document doc = new Document(MyDir + @"in.docx");

FindReplaceOptions opts = new FindReplaceOptions();
opts.Direction = FindReplaceDirection.Backward;
opts.ReplacingCallback = new StructuredTagReplaceEvaluator();

doc.Range.Replace(new System.Text.RegularExpressions.Regex("CHECKBOX"), "", opts);

doc.Save(MyDir + @"17.8.docx");

public class StructuredTagReplaceEvaluator : IReplacingCallback
{
    public ReplaceAction Replacing(ReplacingArgs e)
    {
        Node currentNode = e.MatchNode;

        if (e.MatchOffset > 0)
            currentNode = SplitRun((Run)currentNode, e.MatchOffset);

        ArrayList runs = new ArrayList();

        int remainingLength = e.Match.Value.Length;

        while ((remainingLength > 0) &&
                (currentNode != null) &&
                (currentNode.GetText().Length <= remainingLength))
        {
            runs.Add(currentNode);
            remainingLength = remainingLength - currentNode.GetText().Length;
            do
            {
                currentNode = currentNode.NextSibling;
            }
            while ((currentNode != null)
            && (currentNode.NodeType != NodeType.Run));
        }
                
        if ((currentNode != null) && (remainingLength > 0))
        {
            SplitRun((Run)currentNode, remainingLength);
            runs.Add(currentNode);
        }
                
        StructuredDocumentTag cbx = new StructuredDocumentTag((Document)e.MatchNode.Document, SdtType.Checkbox, MarkupLevel.Inline);
        cbx.Checked = true;

        DocumentBuilder builder = new
        DocumentBuilder((Document)e.MatchNode.Document);

        builder.MoveTo((Run)runs[runs.Count - 1]);
        builder.InsertNode(cbx);

        foreach (Run run in runs)
            run.Remove();

        return ReplaceAction.Skip;
    }
}
        
private static Run SplitRun(Run run, int position)
{
    Run afterRun = (Run)run.Clone(true);
    afterRun.Text = run.Text.Substring(position);
    run.Text = run.Text.Substring(0, position);
    run.ParentNode.InsertAfter(afterRun, run);
    return afterRun;
}

Hope, this helps.

Best regards,

@awais.hafeez this is perfect.

Thanks so much for the great support.