How to Convert a String to Rtf in C#

How to convert a string to RTF in C#?

Doesn't RichTextBox always have the same header/footer? You could just read the content based on off-set location, and continue using it to parse. (I think? please correct me if I'm wrong)

There are libraries available, but I've never had good luck with them personally (though always just found another method before fully exhausting the possibilities). In addition, most of the better ones are usually include a nominal fee.


EDIT
Kind of a hack, but this should get you through what you need to get through (I hope):

RichTextBox rich = new RichTextBox();
Console.Write(rich.Rtf);

String[] words = { "Européen", "Apple", "Carrot", "Touché", "Résumé", "A Européen eating an apple while writing his Résumé, Touché!" };
foreach (String word in words)
{
rich.Text = word;
Int32 offset = rich.Rtf.IndexOf(@"\f0\fs17") + 8;
Int32 len = rich.Rtf.LastIndexOf(@"\par") - offset;
Console.WriteLine("{0,-15} : {1}", word, rich.Rtf.Substring(offset, len).Trim());
}

EDIT 2

The breakdown of the codes RTF control code are as follows:

  • Header
    • \f0 - Use the 0-index font (first font in the list, which is typically Microsoft Sans Serif (noted in the font table in the header: {\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}}))
    • \fs17 - Font formatting, specify the size is 17 (17 being in half-points)
  • Footer
    • \par is specifying that it's the end of a paragraph.

Hopefully that clears some things up. ;-)

converting txt to rtf

Just add text into empty RTF template, plain text doesn't have any formating anyway, so let's say that rtf template looks like this (from wikipedia example):

{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard _TEXT_CONTENT_HERE_ }

Update: I forgot about new lines, braces and backslashes :)

public static string PlainTextToRtf(string plainText)
{
string escapedPlainText = plainText.Replace(@"\", @"\\").Replace("{", @"\{").Replace("}", @"\}");
string rtf = @"{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\pard ";
rtf += escapedPlainText.Replace(Environment.NewLine, @" \par ");
rtf += " }";
return rtf;
}

How to create RTF from plain text (or string) in C#?

I'd use an external library instead of coding your own. Check these projects:

  • http://sourceforge.net/projects/netrtfwriter/
  • http://www.codeproject.com/Articles/11306/NRTFTree-A-class-library-for-RTF-processing-in-C

You might also be able to use the Rtf property of the RichTextBox control (if your users are entering data in such a control).

How to convert convert string to RTF format in RichTextBox inside a DataTemplate of a DataGrid?

  1. Create your own RichTextBox, and introduce a new DependencyProperty called TextProperty.

    public class MyRichTextBox : RichTextBox
    {
    public string Text
    {
    get { return (string)GetValue(TextProperty); }
    set { SetValue(TextProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Text. This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text", typeof(string), typeof(MyRichTextBox), new PropertyMetadata(String.Empty, new PropertyChangedCallback(TextChanged_Handler)));

    private static void TextChanged_Handler(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
    RichTextBox rtb = d as RichTextBox;

    byte[] array = Encoding.ASCII.GetBytes(e.NewValue.ToString());
    using (MemoryStream stream = new MemoryStream(array))
    {
    TextRange t = new TextRange(rtb.Document.ContentStart,
    rtb.Document.ContentEnd);
    t.Load(stream, System.Windows.DataFormats.Rtf);
    }
    }
    }

Usage :

<local:MyRichTextBox Margin="20" Text="{Binding RtfCol}" Width="300" Height="300" />

  1. You can also take the route of AttachedProperty.


Related Topics



Leave a reply



Submit