Hi,
Thanks for your inquiry.
After getting the TextSelection[], you can loop through it and get the TextRange’s detailed information, such as the index of its located paragraph, then you can replace the text in some specific paragraphs. You can see my code for reference.
- Code: Select all
//key:index of paragraph
Dictionary<int, TextRange[]> dic = new Dictionary<int, TextRange[]>();
Document doc = new Document();
doc.LoadFromFile("sample.docx");
Regex regex = new Regex("\\#\\w+\\b");
// find the text
TextSelection[] selections = doc.FindAllPattern(regex);
int index = 0;
int lastParagraphIndex = 0;
foreach (TextSelection selection in selections)
{
TextRange range = selection.GetAsOneRange();
// get range's owner paragraph
Paragraph paragraph = range.OwnerParagraph;
// get the paragraph's owner body
DocumentObject documentObject = paragraph.Owner;
//get the body's owner section
Section section = (Section)documentObject.Owner;
// get the index of specific paragraph
int paragraphIndex = section.Paragraphs.IndexOf(paragraph);
if(paragraphIndex != lastParagraphIndex){
index = 0;
}
if (dic.ContainsKey(paragraphIndex))
{
dic[paragraphIndex][index++] = range;
}
else
{
TextRange[] tra = new TextRange[selections.Length];
tra[index++] = range;
dic[paragraphIndex] = tra;
}
lastParagraphIndex = paragraphIndex;
}
// for example, replace the second paragrraph's second textrange.
int replaceParaIndx = 1;
int replaceTRIndex = 1;
string replaceText = "spire";
foreach (int i in dic.Keys)
{
if (i == replaceParaIndx)
{
TextRange tr = dic[i][replaceTRIndex];
tr.Text = replaceText;
}
}
doc.SaveToFile("output.docx", FileFormat.Docx);
If the code does not meet your requirement, could you please provide us with the following messages? You can send them to us via email (
[email protected]) or attach them here. Thanks for your assistance.
1) some sample files.
2) the effect you want to achieve.
Sincerely,
Triste
E-iceblue support team