Shift Move Cursor to Right by 10 Count of Characters in Paragraph of Word Document from Current Position using C# .NET

Need help…

could you please tell us how we can identify the number of characters in word and the character index of current cursor location and move left or right from the current to a specific count.


Hi there,

Thanks for your inquiry. Please note that all text of the document is stored in runs of text. A single word may have single or multiple Run nodes.

You are looking for a way to move to a particular character position in a Paragraph. Unfortunately, Aspose.Words does not support the requested feature at the moment. However, we have logged this feature request as WORDSNET-10148 in our issue tracking system. You will be notified via this forum thread once this feature is available. We apologize for your inconvenience.

You can move the cursor to the start or end of paragraph using DocumentBuilder.MoveToParagraph(int paragraphIndex, int characterIndex) method.

Using the characterIndex, you can specify the index of the character inside the paragraph. Currently you can only specify 0 to move to the beginning of the paragraph or -1 to move to the end of the paragraph.

@boris.reznichenko,

Regarding WORDSNET-10148, you may use the following code as a workaround. Please see these sample input/output Word documents (Docs.zip (17.6 KB)). Hope, this helps:

int paragraphIndex = 0;
int characterIndex = 4;
string text = "demo";

Document doc = new Document(@"E:\\Temp\\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

Paragraph targetPara = (Paragraph)builder.CurrentStory.GetChildNodes(NodeType.Paragraph, true)[paragraphIndex];
Node[] runs = targetPara.GetChildNodes(NodeType.Run, true).ToArray();

for (int i = 0; i < runs.Length; i++)
{
    Run run = (Run)runs[i];
    int length = run.Text.Length;

    Run currentNode = run;
    for (int x = 1; x < length; x++)
    {
        currentNode = SplitRun(currentNode, 1);
    }
}

if (characterIndex >= 0 && characterIndex < targetPara.Runs.Count)
{
    builder.MoveTo(targetPara.Runs[characterIndex]);
    builder.Font.Name = "Verdana";
    builder.Font.Size = 16;
    builder.Font.Color = Color.Red;
    builder.Write(text);
}
else
{
    Console.WriteLine("Incorrect character index specified");
}

doc.JoinRunsWithSameFormatting();
doc.Save(@"E:\\Temp\\20.3.docx");

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), (0) + (position));
    run.ParentNode.InsertAfter(afterRun, run);
    return afterRun;
}

We will also inform you via this thread as soon as WORDSNET-10148 will be resolved in future.

The issues you have found earlier (filed as WORDSNET-10148) have been fixed in this Aspose.Words for .NET 21.2 update and this Aspose.Words for Java 21.2 update.