Search code examples
c#ms-wordspire.doc

How to get line color from Word [C#][Spire.Doc]


I have the word document which text like this. In my own little project I convert .doc or .docx document to .txt file via Spire.Doc and get lines by one by, then do with them some work, but now there appeared a multi-colored text and I need to get a red line as follows: Get the Word lines by one by and if the line color is not black, then add this colored line to string. I want to ignore text colored black, and get line with red text. How can I do this?


Solution

  • You can use the following code to get text in red color:

    Document document = new Document();
    document.LoadFromFile("2.docx");
    
    Section section = document.Sections[0];
    
    StringBuilder sb = new StringBuilder();
    
    foreach (Paragraph paragraph in section.Paragraphs)
    {
    
    foreach (DocumentObject obj in paragraph.ChildObjects)
    {
        if (obj is TextRange)
        {
            TextRange tr = obj as TextRange;
    
            if (tr.CharacterFormat.TextColor.ToArgb() == Color.Red.ToArgb())
            {
                sb.AppendLine(tr.Text);
            }
        }
    }
    
    File.WriteAllText("RedText.txt", sb.ToString());