Inicio Proyectos Librería NRtfTree Ejemplos NRtfTree

Ejemplos NRtfTree

por sgoliver

Esta página trata de mostrar las características básicas de la librería NRtfTree mediante ejemplos sencillos. Veremos cómo cargar documentos y trabajar con los árboles RTF resultantes.

I. Trabajando con árboles RTF

  1. Cargar un documento RTF desde un fichero.
  2. Cargar un documento RTF desde una cadena de texto.
  3. Guardar un árbol RTF a un fichero.
  4. Obtener el código RTF de un árbol.
  5. Obtener el árbol RTF de un documento.
  6. Obtener la tabla de colores.
  7. Obtener la tabla de fuentes.
  8. Obtener las propiedades de un documento.

II. Trabajando con nodos RTF

  1. Obtener el código RTF de un nodo.
  2. Tipo, clave y texto de un nodo.
  3. Parámetro de un nodo.
  4. Navegación de nodos.
  5. Buscar nodos por clave.
  6. Buscar nodos por tipo.
  7. Crear nuevos nodos.
  8. Añadir nodos al árbol.
  9. Nodos de imagen.
  10. Nodos de objeto.

I. Trabajando con árboles RTF

Cargar un documento RTF desde un fichero

//Create an RTF object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

Cargar un documento RTF desde una cadena de texto

//RTF document in a string
String rtfText = 
          @"{\rtf1\ansi\ansicpg1252\deff0\deflang1034\deflangfe1034\deftab708" +
          @"{\fonttbl{\f0\froman\fprq2\fcharset0 Times New Roman;}}" +
          @"\viewkind4\uc1\pard\nowidctlpar\lang3082\f0\fs24 example\par}";

//Create an RTF object
RtfTree tree2 = new RtfTree();

//Load an RTF document from a string
tree2.LoadRtfText(rtfText);

Guardar un árbol RTF a un fichero

//RTF document in a string
String rtfText = 
          @"{\rtf1\ansi\ansicpg1252\deff0\deflang1034\deflangfe1034\deftab708" +
          @"{\fonttbl{\f0\froman\fprq2\fcharset0 Times New Roman;}}" +
          @"\viewkind4\uc1\pard\nowidctlpar\lang3082\f0\fs24 example\par}";

//Create an RtfTree object
RtfTree tree = new RtfTree();

//Load an RTF document from a string
tree.LoadRtfText(rtfText);

//Save the RTF document to a file
tree.SaveRtf("c:\\Example-SaveRtf.rtf");

Obtener el código RTF de un árbol

//Create an RtfTree object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Get and print RTF code
Console.Write(tree.Rtf);

Obtener el árbol RTF de un documento

//Create an RtfTree object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Get and print RTF code
Console.Write(tree.ToStringEx());
----------------------------------------------------
                     OUTPUT
----------------------------------------------------

ROOT
  GROUP
    KEYWORD: rtf 1
    KEYWORD: ansi
    KEYWORD: ansicpg 1252
    KEYWORD: deff 0
    KEYWORD: deflang 1034
    KEYWORD: deflangfe 1034
    KEYWORD: deftab 708
    GROUP
      KEYWORD: fonttbl
      GROUP
        KEYWORD: f 0
        KEYWORD: froman
        KEYWORD: fprq 2
        KEYWORD: fcharset 0
        TEXT: Times New Roman;
      GROUP
        KEYWORD: f 1
        KEYWORD: fswiss
        KEYWORD: fprq 2
        KEYWORD: fcharset 0
        TEXT: Arial;
    GROUP
      KEYWORD: colortbl
      TEXT: ;
      KEYWORD: red 255
      KEYWORD: green 0
      KEYWORD: blue 0
      TEXT: ;
      KEYWORD: red 51
      KEYWORD: green 153
      KEYWORD: blue 102
      TEXT: ;
    ...
    KEYWORD: viewkind 4
    KEYWORD: uc 1
    KEYWORD: pard
    KEYWORD: nowidctlpar
    KEYWORD: lang 3082
    KEYWORD: f 0
    KEYWORD: fs 24
    TEXT: Esto es una prueba para 
    KEYWORD: cf 1
    TEXT: probar
    ...

Obtener la tabla de colores

//Create an RtfTree object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Get Font Table
RtfFontTable fonts = tree.GetFontTable();

//Print Font Table
foreach(int i=0; i<fonts.Count; i++)
{
    Console.WriteLine(fonts&#91;i&#93;);
}
&#91;/sourcecode&#93;

<strong><a name="example7">Obtener la tabla de fuentes</a></strong>

//Create an RtfTree object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Get Color Table
RtfColorTable colors = tree.GetColorTable();

//Print Color Table
foreach(int i=0; i<colors.Count; i++)
{
    Console.WriteLine(colors&#91;i&#93;);
}
&#91;/sourcecode&#93;

<strong><a name="example8">Obtener las propiedades de un documento</a></strong>

//Create an RtfTree object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Get Document Properties
InfoGroup info = tree.GetInfoGroup();

//Print some Document Properties
Console.WriteLine("Author: " + info.Author);
Console.WriteLine("Subject: " + info.Subject);
Console.WriteLine("Title: " + info.Title);
Console.WriteLine("Category: " + info.Category);
Console.WriteLine("Num. of Chars: " + info.NumberOfChars);

II. Trabajando con nodos RTF

Obtener el código RTF de un nodo

//Create an RTF object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Search Font Table Node
RtfTreeNode ftNode = tree.RootNode.SelectSingleNode("fonttbl");

//Get Font Table Group
RtfTreeNode ftGroup = ftNode.ParentNode;

//Print RTF code
Console.Write(ftGroup.Rtf);

Tipo, clave y texto de un nodo

//Create an RTF object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Search Font Table Node
RtfTreeNode ftNode = tree.RootNode.SelectSingleNode("fonttbl");

//Search first Text Node
RtfTreeNode textNode = 
tree.RootNode.FirstChild.SelectSingleChildNodeByType(RtfNodeType.Text);

//If (NodeType == Keyword) --> NodeKey returns the keyword
Console.WriteLine("Node type: " + ftNode.NodeType);
Console.WriteLine("Node key: " + ftNode.NodeKey);

//If (NodeType == Text) --> NodeKey returns the text
Console.WriteLine("Node type: " + textNode.NodeType);
Console.WriteLine("Node key: " + textNode.NodeKey);

Parámetro de un nodo

//Create an RTF object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Search First \fs keyword (font size keyword)
RtfTreeNode fsNode = tree.RootNode.SelectSingleNode("fs");

//Print parameter and value
Console.WriteLine("Has Parameter? : " + fsNode.HasParameter);
Console.WriteLine("Parameter Value: " + fsNode.Parameter);

Navegación entre nodos

//Create an RTF object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Get Root Node
RtfTreeNode node = tree.RootNode;
Console.WriteLine("Root Node: " + node);

//Get First Child
node = node.FirstChild;
Console.WriteLine("First Child: " + node);

//Get First Child
node = node.FirstChild;
Console.WriteLine("First Child: " + node);

//Get Next Sibling
node = node.NextSibling;
Console.WriteLine("Next Sibling: " + node);

//Get Parent Node
node = node.ParentNode;
Console.WriteLine("Parent Node: " + node);

Buscar nodos por clave

//Create an RTF object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Search the first "\fs" keyword
RtfTreeNode node = tree.RootNode.SelectSingleNode("fs");
Console.WriteLine("First \\fs keyword: " + node);

//Search all the "\cf" keywords:
RtfNodeCollection nodes = tree.RootNode.SelectNodes("cf");
Console.WriteLine("All \\cf keywords: ");
foreach(RtfTreeNode n in nodes)
Console.WriteLine("\t" + n);

Buscar nodos por tipo

//Create an RTF object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Search the first "\fs" keyword
RtfTreeNode node = tree.RootNode.SelectSingleNodeByType(RtfNodeType.Control);
Console.WriteLine("First control node: " + node);

//Search all the "\cf" keywords:
RtfNodeCollection nodes = tree.RootNode.SelectNodesByType(RtfNodeType.Control);
Console.WriteLine("All control nodes: ");
foreach(RtfTreeNode n in nodes)
Console.WriteLine("\t" + n);

Crear nuevos nodos

//Create a default node
RtfTreeNode defaultNode = new RtfTreeNode();

//Create a Keyword node
RtfTreeNode typeNode = new RtfTreeNode(RtfNodeType.Keyword);

//Create a full node (Type, Key, HasParameter, Parameter)
RtfTreeNode fullNode = new RtfTreeNode(RtfNodeType.Keyword, "cf", true, 1);

Añadir nuevos nodos al árbol

//Create an RTF object
RtfTree tree = new RtfTree();

//Load an RTF document from a file
tree.LoadRtfFile("c:\\example.rtf");

//Create a new nodes
RtfTreeNode newLineNode = new RtfTreeNode(RtfNodeType.Keyword,"par",false,0);
RtfTreeNode textNode = new RtfTreeNode(RtfNodeType.Text,"New Text",false,0);

//Append the new node to the tree
tree.RootNode.FirstChild.AppendChild(newLineNode);
tree.RootNode.FirstChild.AppendChild(textNode);

//Save the document
tree.SaveRtf("c:\\newDocument.rtf");

Nodos de imagen

//Create an RTF object
RtfTree arbol = new RtfTree();

//Load an RTF document from a file
arbol.LoadRtfFile("example2.rtf");

//Search all "\pict" nodes (Images)
RtfNodeCollection imageNodes = arbol.RootNode.SelectNodes("pict");

//Save all found images
int i = 1;
foreach (RtfTreeNode node in imageNodes)
{
    //Create an image node
    ImageNode imageNode = new ImageNode(node.ParentNode);

    //Save the image with its original format
    imageNode.SaveImage("image" + i + "." + 
                                   getExtension(imageNode.ImageFormat));

    i++;
}

Nodos de objeto

//Create an RtfTree object
RtfTree arbol = new RtfTree();

//Load an RTF document from a file
arbol.LoadRtfFile("example3.rtf");

//Search the first Object keyword
RtfTreeNode node = arbol.RootNode.SelectSingleNode("object");

//Create an Object Node
ObjectNode objectNode = new ObjectNode(node.ParentNode);

//Print some object information
txtArbol.Text += "Object type: " + objectNode.ObjectType + "\r\n";
txtArbol.Text += "Object class: " + objectNode.ObjectClass + "\r\n";

//Get the "\result" node
RtfTreeNode resultNode = objectNode.ResultNode;

RtfTreeNode auxNode = null;

//If an image exists in the "\result" group
if ((auxNode = resultNode.SelectSingleNode("pict")) != null)
{
    //Create an image node
    ImageNode imageNode = new ImageNode(auxNode.ParentNode);

    //Print some image information
    txtArbol.Text += "Image width: " + imageNode.Width/20 + "\r\n";
    txtArbol.Text += "Image heigh: " + imageNode.Height/20 + "\r\n";
    txtArbol.Text += "Image format: " + imageNode.ImageFormat + "\r\n";

    //Save the image
    MessageBox.Show("File: image-example3." + 
                             getExtension(imageNode.ImageFormat));

    imageNode.SaveImage("image-example3." + 
                                   getExtension(imageNode.ImageFormat));
}
else
{ 
    MessageBox.Show("'\result' node contains no images!");
}

1 comentario

Publicado NRtfTree 0.3.0 beta 2 | sgoliver.net blog 18/07/2009 - 6:46

[…] donde ire colocando las consultas que más me suelen llegar por correo electrónico, y una nueva sección de ejemplos que espero ir actualizando con pequeños fragmentos de código con los casos de uso más comunes de […]

Comentarios cerrados.

Este sitio web utiliza cookies para que usted tenga la mejor experiencia de usuario. Si continúa navegando está dando su consentimiento para la aceptación de las mencionadas cookies y la aceptación de nuestra política de cookies, pinche el enlace para mayor información. Aceptar Más Información

Política de Privacidad y Cookies