Click here to Skip to main content
Click here to Skip to main content

NRTFTree - A class library for RTF processing in C#

By , 7 Sep 2007
 
NRtfTree Demo Screenshot

Introduction

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.

Background

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:

Examples

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
        tree.LoadRtfFile("c:\rtfdoc.rtf");
        
        //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)
            {
                switch(nodo.NodeKey)
                    {
                    case "f":  //Font type
                    //...
                    break;
                case "cf":  //Font color
                    //...
                    break;
                case "fs":  //Font size
                    //...
                    break;
                }
            }
            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)
        {
            switch(key)
            {
               case "b":  //bold font
                    //...
                    break;
               case "i":  //Italic font
                    //...
                    break;
               //...
            }
        }
    
        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
    reader.LoadRtfFile(rutaRTF);
    
    //Start parsing
    reader.Parse();
  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);
    doc.AddNewLine();
    doc.AddNewLine();
    
    format.size = 12;
    format.bold = false;
    format.underline = false;
    
    doc.AddText("This is a test.", format); 
    doc.AddText("This is a text.");
    
    doc.AddNewLine();
    
    doc.AddImage("test.png", 50, 50);
    
    doc.Close();

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).

References

History

  • 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.

License

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

About the Author

sgoliver
Web Developer
Spain Spain
Member
Currently, i work for a great consulting company as a software developer.
 
My homepage is:
http://www.sgoliver.net

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 4memberDiwakar Gupta24 Mar '13 - 22:57 
QuestionA few enhancementsmemberTodd C. Gleason11 Sep '12 - 17:58 
QuestionNRTFTree works incorrect with Unicode, please help [modified]memberWin32nipuh10 Aug '12 - 1:12 
SuggestionRe: NRTFTree works incorrect with Unicode, please helpmemberPartyboyone13 Aug '12 - 4:16 
GeneralRe: NRTFTree works incorrect with Unicode, please helpmemberWin32nipuh5 Sep '12 - 2:44 
Questionnot working for tablememberkalyan105224 May '12 - 3:56 
GeneralMy vote of 5membermanoj kumar choubey9 Feb '12 - 3:06 
GeneralDrawStringRTFmemberMartin Welker10 Mar '10 - 1:05 
QuestionCan it works under windows CE 5.0?memberliuzhu541928 Jan '10 - 15:35 
GeneralBackground colormemberilean3 Jan '10 - 0:49 
GeneralMany ThanksmemberBruceG17 Feb '09 - 11:55 
GeneralRe: Many ThanksmemberLGNG9 Jul '09 - 8:50 
QuestionWhen will the final version of v0.3.0 be available?memberkmillard5924 Nov '08 - 9:23 
GeneralRtfTree not working even i have given refence of .DLLmemberspatil198221 Nov '08 - 0:48 
GeneralRe: RtfTree not working even i have given refence of .DLLmemberMember 899618718 May '12 - 9:02 
QuestionWrong dimension wmetafile imagesmemberNickBlu11 Nov '08 - 18:50 
GeneralNRtfTree Merge multiple RTF docmemberBoFabio24 Oct '08 - 0:01 
GeneralRe: NRtfTree Merge multiple RTF docmemberVifani9 Dec '08 - 5:16 
GeneralRe: NRtfTree Merge multiple RTF docmemberkevin.yan14 Jun '09 - 20:29 
GeneralNRtfTree bug fixmemberBoFabio23 Oct '08 - 23:53 
GeneralRe: NRtfTree bug fixmemberWin32nipuh18 Jun '09 - 5:35 
GeneralbugfixmemberMember 226412521 Aug '08 - 0:20 
GeneralTraductorRtf in DelphimemberNicolò Blunda8 Aug '08 - 11:17 
GeneralIf text loaded isn't RTF, .text property crashes. [modified]membergerbilvomit6 Aug '08 - 10:06 
GeneralMerging RTF documentsmemberOlli Nissinen17 Jun '08 - 23:32 
GeneralRe: Merging RTF documentsmemberBoFabio24 Oct '08 - 0:09 
GeneralRe: Merging RTF documentsmembersergio.excelium17 Apr '09 - 1:11 
GeneralRe: Merging RTF documentsmembersergio.excelium17 Apr '09 - 2:50 
GeneralIssue with other charactersets!memberMember 354931428 May '08 - 0:04 
QuestionMerge Codesmemberbeachbeamer15 May '08 - 15:55 
QuestionHow I Can Find and Replace textmemberladakana3 Apr '08 - 21:11 
AnswerRe: How I Can Find and Replace textmemberRuberoid30 Apr '09 - 5:34 
QuestionRe: How I Can Find and Replace textmembersgoliver1 May '09 - 0:11 
AnswerRe: How I Can Find and Replace textmemberssomasek4 May '09 - 8:46 
AnswerRe: How I Can Find and Replace textmemberGary Michalek13 Nov '09 - 10:29 
GeneralHTMLmemberPQSIK24 Nov '07 - 12:12 
AnswerRe: HTML [modified]membersgoliver25 Nov '07 - 22:11 
GeneralOut of memory exceptionmemberOrsol26 Sep '07 - 22:58 
AnswerRe: Out of memory exceptionmembersgoliver29 Sep '07 - 1:55 
GeneralRe: Out of memory exceptionmemberMember 3238374 Apr '08 - 8:00 
AnswerRe: Out of memory exceptionmembersgoliver5 Apr '08 - 4:42 
GeneralIts fantastic, but the table in rtf is not get parsed [modified]memberchand.m25 May '07 - 1:19 
GeneralC++ conversion of the Librarymemberalamgir mohammed16 Jan '07 - 17:25 
AnswerRe: C++ conversion of the Librarymembersgoliver19 Jan '07 - 8:32 
I have just published in my web a new version of the library written in C++.
 
CRtfTree: http://www.sgoliver.net/crtftree.html
 
Note: I'm not the author of this version so I don't offer support for it.
GeneralRe: C++ conversion of the Librarymembercode_discuss21 Mar '08 - 20:33 
GeneralRe: C++ conversion of the Librarymembersgoliver30 Mar '08 - 3:43 
GeneralRe: C++ conversion of the Librarymemberemadns9 Jul '08 - 6:36 
GeneralRe: C++ conversion of the Librarymembersgoliver2 Nov '08 - 10:16 
GeneralRe: C++ conversion of the LibrarymemberMember 30874068 Jan '09 - 20:35 
General'Font TablememberHolpit15 Jan '07 - 23:35 

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

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