RTFBuilder

Every so often you come across a requirement that can be solved by an ‘old’ technology. Yes, us old ‘bru’s’ still can make a difference here and there… I needed a way to display formatted data that can also be easily edited, saved, printed, exported. Sure, html can be used as well but it is sometimes a shlep manipulating the data inside the application and it is sorta bloated. Years ago – even before html existed (or was widely used) there was a standard document format called Rich Text Format. It was compact, can be read/written by most word processors, and do lots of funky stuff. Even today Visual Studio has a control that specifically make use of this format.

Unlike html the rtf raw format isn’t exactly easy to read or understand but you don’t need to be an expert to use it. In VS you can simply use the the RTF control to programatically add and format text (on a side-note the format also allow embedding images and other stuff). This works fine for smallish documents. If however you need to create a big or long document you need to go ‘raw’ or use this library I discovered on Codeproject.  This library actually implements a way so you can build up a document similar to a StringBuilder – this makes it very fast. Using it is also fairly easy as it implements an Method based formatting concept. This is best explained with an example:

RTFBuilder rtfBuilder = new RTFBuilder();
//the following line adds a line of text using the font Courier New size 10
rtfBuilder.Font(RTFFont.CourierNew).FontSize(10).AppendLine("Some text");
//the following line adds a bold line of text
rtfBuilder.FontStyle(FontStyle.Bold).AppendLine("Some bold text");
//the following line write blue text on a black background
rtfBuilder.ForeColor(Color.Blue).BackColor(Color.Black).AppendLine("Blue on black");

//then if you want to see what the raw rtf text looks like
string rtfData = rtfBuilder.ToString();
//then finally you can set the rtftext of an RTFControl like this:
rtfControl.Rtf = rtfData;

Really simple hey?

So what is this good for? Well since the content is now inside an rtf control it can now be edited by a user – yes that is right, the rtf control allows for editing the content just like a plain old text box except you can also change the formatting – in fact, using the rtf control you can build a fully working word processor since that is what it was intended to do! Once you’re done editing or formatting the control allows for saving or easily exporting the content. Printing is still a bit tricky but even for that there are examples on the web. Remember that you can copy & paste formatted text from and to the rtf control as well. Now, try to do all that with html and a web browser control! hehe

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>