Free Support Forum - aspose.com

Changing Font in an existing docuemnt

I got some problem with changing fornt property in the document.

Sample code is

public void SearchAndReplace(string strSearch, string strReplace)

{

try

{

DocumentBuilder oDocbuilder = new DocumentBuilder(m_oOutDoc);

Aspose.Words.Font oFont = oDocbuilder.Font;

oFont.Color = System.Drawing.Color.Black;

oDocbuilder.Font.Size = 20;

Range oRange = m_oOutDoc.Range;

int nReplace = oRange.Replace(strSearch, "", false, false);

if (nReplace != 0)

{

oDocbuilder.Write(strReplace);

}

}

catch (Exception oEx)

{

string strExp = oEx.Message;

}

}

In this perticuler example when i tried to change property of the font, i was not showing any changes in the document.

Thank you

Hi

Thanks for your inquiry. I think that you should use ReplaceEvaluator. For example see the following code.

string strSearch = "test";

string strReplace = "111";

public void TestReplace_106531()

{

Document doc = new Document(@"423_106531_prasanth.skumar\in.doc");

Regex regex = new Regex(strSearch);

doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceAction_106531), true);

doc.Save(@"423_106531_prasanth.skumar\out.doc");

}

ReplaceAction ReplaceAction_106531(object sender, ReplaceEvaluatorArgs e)

{

Run run1 = (Run)e.MatchNode;

Run run2 = new Run(e.MatchNode.Document);

Run run3 = new Run(e.MatchNode.Document);

run3.Text = run1.Text.Substring(0, run1.Text.IndexOf(e.Match.Value));

run2.Text = strReplace;

run1.Text = run1.Text.Substring(run1.Text.IndexOf(e.Match.Value) + e.Match.Value.Length);

run2.Font.Size = 20;

run2.Font.Color = Color.Red;

run1.ParentParagraph.InsertBefore(run3, run1);

run1.ParentParagraph.InsertBefore(run2, run1);

return ReplaceAction.Skip;

}

The input document contains the following text.

“Some text before test some text after”

The output is “Some text before 111 some text after”

I hope that this will help you.

Best regards.