Search code examples
c#rtfstringwriter

Tab mis-interpreted by RichTextBox


I have RTF that is being mis-interpreted. StringWriter takes a \t and replaces it with some character that RichTextBox cannot deal with inside a table.

string rtfBeforeConversion = @"{\rtf1{\trowd\cellx1150 \cellx3750 \cellx7350 Temp\intbl\cell 96 - 99.7\t\intbl\cell 97.9\t\intbl\cell \row}}";
string rtfBrokenByConversion = @"{\rtf1{\trowd\cellx1150 \cellx3750 \cellx7350 Temp\intbl\cell 96 - 99.7    \intbl\cell 97.9    \intbl\cell \row}}";

rtfBeforeConversion correctly displays 3 columns with data in a RichTextBox.

rtfBrokenByConversion results in the 3rd column displaying no data (or data outside and to the right of it's column depending on the DLL being used to interpret the RTF).

Stringwriter code

 using (StringWriter sw = new StringWriter())
            {
                GetRTF(sw);//inserts value of rtfBeforeConversion
                return sw.ToString();//ToString() creates rtfBrokenByConversion
            }

How can I correct this problem? (Note that I tried StringBuilder and had the same results)


Solution

  • Like other special characters \r, \n,, \t cannot be readily used inside of RTF. The character needs to be converted to it's RTF equivalent. In this case I created an extension to clean the ill formatted text:

        public static string ConvertTabs(this string poorlyFormedRtf)
        {
            string unicodeTab = "\u0009";
            string result = poorlyFormedRtf.Replace(unicodeTab, "\\tab");
            return result;
        }
    

    Now everything looks great.