Click here to Skip to main content
13,737,288 members
Click here to Skip to main content
Add your own
alternative version


157 bookmarked
Posted 13 Aug 2005
Licenced LGPL3

NRTFTree - A class library for RTF processing in C#

, 7 Sep 2007
Rate this:
Please Sign up or sign in to vote.
Class library to manage RTF files.
NRtfTree Demo Screenshot


NRtfTree Library (LGPL) is a set of classes written entirely in C# that may be used to manage RTF documents in your own applications. NRtfTree will help you:

  • Open and parse RTF files.
  • Analyze the content of RTF files.
  • Add, modify and remove document elements (i.e. text, control words, control symbols).
  • Create new RTF documents.


RTF (Rich Text Format) is a method of encoding formatted text and graphics for easy transfer between applications. An RTF document can contain text, images, tables, lists, hyperlinks and many other text and graphic elements. In addition, RTF is the format used internally by the RichTextBox control included as part of .NET Framework. Nevertheless, its functionality is not enough to satisfy all aspects of RTF file management.

Using the Code

NRtfTree has two modes of operation:

  1. DOM-like mode: RTF documents are loaded in a tree structure and are provided several methods to traverse it, access tag contents and modify or create new nodes. This implementation requires the entire content of a document to be parsed and stored in memory.

    In this mode, the main classes are RtfTree and RtfTreeNode:

  2. SAX-like mode: RTF file parser is implemented as an event-driven model in which the programmer provides callback methods that are invoked by the parser as part of its traversal of the RTF document.

    In this mode, the main classes are RtfReader and SARParser:


The following lines show how you can use the class library in your own code.

  1. DOM-like mode

    This code loads an RTF document into an RtfTree object and inspects all the child nodes:

    public void doSomething()
        //Create the RTF tree object
        RtfTree tree = new RtfTree();
        //Load and parse RTF document
        //Get root node
        RtfTreeNode root = tree.RootNode;
        RtfTreeNode node = new RtfTreeNode();
        for(int i = 0; i < root.ChildNodes.Count; i++)
            node = root.ChildNodes[i];
            if(node.NodeType == RTF_NODE_TYPE.GROUP)
            else if(node.NodeType == RTF_NODE_TYPE.CONTROL)
            else if(node.NodeType == RTF_NODE_TYPE.KEYWORD)
                    case "f":  //Font type
                case "cf":  //Font color
                case "fs":  //Font size
            else if(node.NodeType == RTF_NODE_TYPE.TEXT)
  2. SAX-like mode

    This is an example of the implementation of a simple rft sax-parser:

    public class MyParser : SARParser
        public override void StartRtfDocument()
          doc += 
            "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n";
          doc += "<DOCUMENT>\r\n";
        public override void EndRtfDocument()
            doc += "\r\n</DOCUMENT>";
        public override void StartRtfGroup()
        public override void EndRtfGroup()
        public override void RtfControl(string key, 
                                bool hasParam, int param)
        public override void RtfKeyword(string key, 
                                bool hasParam, int param)
               case "b":  //bold font
               case "i":  //Italic font
        public override void RtfText(string text)
            doc += text;

    Once you have completed the parser, you can start parsing the RTF document by calling the function RtfReader.Parse(). Then the handlers for the configured events are automatically called as many times as necessary:

    //Create the parser
    MiParser parser = new MyParser(res);
    //Create the reader and associate the parser
    reader = new RtfReader(parser);
    //Load the RTF document
    //Start parsing
  3. RtfDocument class

    You can create new RTF documents using the new class RtfDocument (beta):

    RtfDocument doc = new RtfDocument("testdoc.rtf");
    RtfTextFormat format = new RtfTextFormat();
    format.size = 20;
    format.bold = true;
    format.underline = true;
    doc.AddText("Title", format);
    format.size = 12;
    format.bold = false;
    format.underline = false;
    doc.AddText("This is a test.", format); 
    doc.AddText("This is a text.");
    doc.AddImage("test.png", 50, 50);

Software License

NRtfTree Library is licensed under the GNU LGPL license.

More Information

You can find up-to-date information on my personal home page (Spanish) or NRtfTree SourceForge Project (English).



  • 2007/09/02 - v0.3.0 beta 1
    • New license: LGPL.
    • New classes to create RTF documents (basic support in beta): RtfDocument, RtfColorTable, RtfFontTable and RtfTextFormat.
    • RtfTree class:
      • New property MergeSpecialCharacters. When it is set to true, if special character is found ('\') it is converted to Text node and eventually merged to adjacent text nodes.
      • New property Text. Returns plain text from the RTF document.
      • New method GetEncoding(). Returns document encoding.
    • RtfTreeNode class:
      • New property Tree. Returns a reference to owner RTF tree.
      • New method To String().
      • New method InsertChild(). Inserts a new node at the specified location.
      • Methods SelectXXXByType() have been replaced by SelectXXX() overloads.
      • New methods SelectSibling() (3 overloads).
    • RtfNodeCollection class:
      • New method Insert(). Inserts a new node at the specified location.
      • New method RemoveRange(). Remove a range of nodes from the list.
    • InfoGroup class:
      • New method ToString().
    • Fixed Bugs:
      • Group and Root node types initialization with "ROOT" and "GROUP".
      • NRtfTree.Rtf property didn't include last '}' in a group node RTF code.
      • NRtfTree does not treat correctly special characters '\', '{' and '}' as part of the text.
      • Methods RtfTreeNode.AppendChild() and InsertChild() should update Root and Tree properties recursively.
  • 2006/12/10 - v0.2.1
    • Fixed - Bug in NRtfTree.SaveRtf() - Special character hex codes with one digit.
  • 2005/12/17 - v0.2.0
    • New namespaces: Net.Sgoliver.NRtfTree.Core and Net.Sgoliver.NRtfTree.Util
    • New classes: ImageNode, ObjectNode, InfoGroup.
    • RtfTreeNode class:
      • New properties: LastChild, NextSibling, PreviousSibling, Rtf.
      • New methods: CloneNode(), HasChildNodes(), SelectSingleNode(), SelectSingleChildNode(), SelectChildNodes(), SelectNodes(), SelectSingleChildNodeType(), SelectChildNodesByType(), SelectNodesByType(), SelectSingleNodeByType().
      • New indexer [equivalent to SelectSingleChildNode()].
      • Some optimization changes.
    • RtfTree class:
      • New methods: ToStringEx(), SaveRtf(), GetColorTable() y GetFontTable() y GetInfoGroup()
      • Some optimization changes.
      • Some bugs fixed.
    • RtfNodeCollection class:
      • New methods: IndexOf(), AddRange()
    • RtfLex class:
      • parseText() now ignores new line, tabs and null characters.
      • Some optimization changes.
  • 2005/08/13 - v0.1
    • First public release.


This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


About the Author

Web Developer
Spain Spain
Currently, i work for a great consulting company as a software developer.

My homepage is:

You may also be interested in...


Comments and Discussions

GeneralRe: C++ conversion of the Library Pin
code_discuss21-Mar-08 20:33
membercode_discuss21-Mar-08 20:33 
GeneralRe: C++ conversion of the Library Pin
sgoliver30-Mar-08 3:43
membersgoliver30-Mar-08 3:43 
GeneralRe: C++ conversion of the Library Pin
emadns9-Jul-08 6:36
memberemadns9-Jul-08 6:36 
GeneralRe: C++ conversion of the Library Pin
sgoliver2-Nov-08 10:16
membersgoliver2-Nov-08 10:16 
GeneralRe: C++ conversion of the Library Pin
8-Jan-09 20:35
member8-Jan-09 20:35 
General'Font Table Pin
Holpit15-Jan-07 23:35
memberHolpit15-Jan-07 23:35 
QuestionMissed code Pin
MTchary29-Dec-06 9:38
memberMTchary29-Dec-06 9:38 
AnswerRe: Missed code Pin
sgoliver4-Jan-07 7:24
membersgoliver4-Jan-07 7:24 
The code is correct. This is a C# feature (and C++, and Java...). In a 'switch' structure you can group several 'case' statements together to execute the same block of code in the three 'cases'. Example:

case RtfTokenType.Keyword:
case RtfTokenType.Control:
case RtfTokenType.Text:
newNode = new RtfTreeNode(tok);
GeneralImages in Rtf document Pin
tmak11-May-06 18:28
membertmak11-May-06 18:28 
AnswerRe: Images in Rtf document [modified] Pin
sgoliver28-May-06 9:12
membersgoliver28-May-06 9:12 
GeneralRe: Images in Rtf document Pin
Super Lloyd26-Jun-06 19:30
memberSuper Lloyd26-Jun-06 19:30 
AnswerRe: Images in Rtf document Pin
sgoliver27-Jun-06 3:28
membersgoliver27-Jun-06 3:28 
GeneralRe: Images in Rtf document Pin
Super Lloyd27-Jun-06 3:39
memberSuper Lloyd27-Jun-06 3:39 
GeneralHTML translation of RTF content Pin
daluu3-Mar-06 13:02
memberdaluu3-Mar-06 13:02 
GeneralRe: HTML translation of RTF content Pin
Flying Jett4-Feb-07 0:34
memberFlying Jett4-Feb-07 0:34 
GeneralRTF engine in C# Pin
angelo778-Jan-06 3:47
memberangelo778-Jan-06 3:47 
AnswerRe: RTF engine in C# Pin
sgoliver8-Jan-06 4:57
membersgoliver8-Jan-06 4:57 
Generalone more problem Pin
kosto2387-Dec-05 4:06
memberkosto2387-Dec-05 4:06 
GeneralProblem Pin
Super Lloyd20-Nov-05 13:00
memberSuper Lloyd20-Nov-05 13:00 
QuestionRTF * Commands Pin
andrew.fry31-Oct-05 22:42
memberandrew.fry31-Oct-05 22:42 
AnswerRe: RTF * Commands Pin
gjacd12-Jan-06 22:22
membergjacd12-Jan-06 22:22 
GeneralRe: RTF * Commands Pin
andrew.fry12-Jan-06 22:31
memberandrew.fry12-Jan-06 22:31 
QuestionEnglish language version? Pin
ChuckC24-Sep-05 2:47
memberChuckC24-Sep-05 2:47 
AnswerRe: English language version? Pin
sgoliver16-Oct-05 9:49
membersgoliver16-Oct-05 9:49 
GeneralRe: English language version? Pin
daluu3-Mar-06 12:56
memberdaluu3-Mar-06 12:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180920.1 | Last Updated 7 Sep 2007
Article Copyright 2005 by sgoliver
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid