I want to call document.Range.Replace passing replacement text that contains at least a \r. This is throwing a exception. How can I over come this. is there some preprocessing I can do to my replacement text to substitute the ControlChar equilivant for my \r?
Hi
Thanks for your request. You can try to use ReplaceEvaluatur to replace this text. See the following example.
public void TestReplaceText_95167()
{
Document doc = new Document(@"200_95167_daithi\in.doc");
Regex regex = new Regex("Text to replace");
doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceAction1), true);
doc.Save(@"200_95167_daithi\out.doc");
}
ReplaceAction ReplaceAction1(object sender, ReplaceEvaluatorArgs e)
{
DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document);
builder.MoveTo(e.MatchNode);
builder.Write("Replaced");
int index = e.MatchNode.Document.FirstSection.Body.Paragraphs.IndexOf(builder.CurrentParagraph);
// insert next paragraph content to current paragraph.
foreach (Run run in e.MatchNode.Document.FirstSection.Body.Paragraphs[index + 1].Runs)
{
builder.CurrentParagraph.AppendChild(run);
}
// remove next paragraph
e.MatchNode.Document.FirstSection.Body.Paragraphs[index + 1].Remove();
return ReplaceAction.Replace;
}
In your example, you hard coded the replacement text to be “Replaced”.
SV-555:
builder.Write(“Replaced”);
I want to pass into the ReplaceEvaluator delegate the replacement text to use. I presume I do this with the sender argument of the delegate…
public delegate ReplaceAction ReplaceEvaluator(object sender, ReplaceEvaluatorArgs e);
I just do not know how to do that at the moment. What type is object sender? I hope you can help.
I am currently calling the doc.Range.Replace method from within a static helper class so I do not have any public properties. Is there any other way to pass this information into the delegate? What is the “object sender” argument used for?
If there is no other solution I will look at rearranging my code.
It appears to work fine for the control characters and keeps the surrounding formatting in my text. Does this seam correct to you or will this code not work in certain scenarios?
Hello!
This should work fine in general. I don’t see potential problems. But we cannot guarantee everything and everywhere. If you find something strange please let us know.
Regards,
I am reading text from xml file. The text contains 2 new lines. _replacement variable is holding this text. When all replacement is done and when I open the generated document, I see that newline chars are replaced with space by Aspose. I think it is wrong behaviour. How to overcome this problem?