Spire.Doc is a professional Word .NET library specifically designed for developers to create, read, write, convert and print Word document files. Get free and professional technical support for Spire.Doc for .NET, Java, Android, C++, Python.

Thu Aug 20, 2020 9:55 am

Hi there,
I would like to know, what is the easiest way to replace string in document along with changing its text color.

Example:
I need to replace string "STR1" (with default black textcolor), with string "STR2" (new red textcolor)

document.Replace("STR1", "STR2", False, True)

Thank you for advices.

bt777_azet.sk
 
Posts: 12
Joined: Thu Apr 23, 2020 8:19 am

Thu Aug 20, 2020 10:26 am

Hello,

Thanks for your inquiry.
Please refer to the following code to achieve your demand. Feel free to contact us if you have further questions.
Code: Select all
        Dim doc As Document = New Document
        doc.LoadFromFile("test.docx")
        Dim textSelections() As TextSelection = doc.FindAllString("STR1", False, True)
        For Each selection As TextSelection In textSelections
            Dim tr As TextRange = selection.GetAsOneRange
            tr.Text = "STR2"
            tr.CharacterFormat.TextColor = Color.Red
        Next
        doc.SaveToFile("out.docx")


Sincerely,
Rachel
E-iceblue support team
User avatar

rachel.lei
 
Posts: 1571
Joined: Tue Jul 09, 2019 2:22 am

Thu Aug 20, 2020 10:47 am

Thank you very much!, It works great :)

bt777_azet.sk
 
Posts: 12
Joined: Thu Apr 23, 2020 8:19 am

Fri Aug 21, 2020 1:04 am

Hello,

Thanks for your prompt response.
Feel free to contact us if you encounter any questions related to our product in the future.
Have a nice day!

Sincerely,
Rachel
E-iceblue support team
User avatar

rachel.lei
 
Posts: 1571
Joined: Tue Jul 09, 2019 2:22 am

Return to Spire.Doc