private RtfTreeNode getReplaceNode() { int replaceID = rtf_replace.Count; RtfTreeNode textNode = new RtfTreeNode(RtfNodeType.Text, "[" + REPLACETAG + "]" + replaceID + "[/" + REPLACETAG + "]", false, 0); return(textNode); }
/// <summary> /// Devuelve el primer nodo del árbol, a partir del nodo actual, cuya palabra clave y parámetro son los indicados como parámetro. /// </summary> /// <param name="keyword">Palabra clave buscada.</param> /// <param name="param">Parámetro buscado.</param> /// <returns>Primer nodo del árbol, a partir del nodo actual, cuya palabra clave y parámetro son ls indicados como parámetro.</returns> public RtfTreeNode SelectSingleNode(string keyword, int param) { int i = 0; bool found = false; RtfTreeNode node = null; while (i < children.Count && !found) { if (children[i].key == keyword && children[i].param == param) { node = children[i]; found = true; } else { node = children[i].SelectSingleNode(keyword, param); if (node != null) { found = true; } } i++; } return(node); }
/// <summary> /// Devuelve la tabla de fuentes del documento RTF. /// </summary> /// <returns>Tabla de fuentes del documento RTF</returns> public RtfFontTable GetFontTable() { RtfFontTable tablaFuentes = new RtfFontTable(); //Buscamos la tabla de fuentes en el árbol RtfTreeNode ntf = MainGroup.SelectSingleGroup("fonttbl"); //Nodo con la tabla de fuentes //Rellenamos el array de fuentes for (int j = 1; j < ntf.ChildNodes.Count; j++) { RtfTreeNode fuente = ntf.ChildNodes[j]; int indiceFuente = -1; string nombreFuente = null; foreach (RtfTreeNode nodo in fuente.ChildNodes) { if (nodo.NodeKey == "f") { indiceFuente = nodo.Parameter; } if (nodo.NodeType == RtfNodeType.Text) { nombreFuente = nodo.NodeKey.Substring(0, nodo.NodeKey.Length - 1); } } tablaFuentes.AddFont(indiceFuente, nombreFuente); } return(tablaFuentes); }
private static void ExtractHyperlinks() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\test-doc.rtf"); RtfNodeCollection fields = tree.MainGroup.SelectGroups("field"); foreach (RtfTreeNode node in fields) { //Extract URL RtfTreeNode fldInst = node.ChildNodes[1]; string fldInstText = ExtractGroupText(fldInst); string url = fldInstText.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)[1]; //Extract Link Text RtfTreeNode fldRslt = node.SelectSingleChildGroup("fldrslt"); string linkText = ExtractGroupText(fldRslt); Console.WriteLine("[" + linkText + ", " + url + "]"); } }
/// <summary> /// Realiza una copia exacta del nodo actual. /// </summary> /// <param name="cloneChildren">Si este parámetro recibe el valor true se clonarán también todos los nodos hijo del nodo actual.</param> /// <returns>Devuelve una copia exacta del nodo actual.</returns> public RtfTreeNode CloneNode(bool cloneChildren) { RtfTreeNode clon = new RtfTreeNode(); clon.key = this.key; clon.hasParam = this.hasParam; clon.param = this.param; clon.parent = this.parent; clon.root = this.root; clon.type = this.type; //Si cloneChildren=false se copia directamente la lista de hijos if (!cloneChildren) { clon.children = this.children; } else //En caso contrario se clonan también cada uno de los hijos, propagando el parámetro cloneChildren=true { clon.children = new RtfNodeCollection(); foreach (RtfTreeNode child in this.children) { clon.children.Add(child.CloneNode(true)); } } return(clon); }
public void SearchNodes() { RtfNodeCollection list1 = new RtfNodeCollection(); RtfTreeNode node = new RtfTreeNode(RtfNodeType.Keyword, "c", true, 3); list1.Add(new RtfTreeNode(RtfNodeType.Keyword, "a", true, 1)); list1.Add(new RtfTreeNode(RtfNodeType.Keyword, "b", true, 2)); list1.Add(node); list1.Add(new RtfTreeNode(RtfNodeType.Keyword, "b", true, 4)); list1.Add(node); list1.Add(new RtfTreeNode(RtfNodeType.Keyword, "e", true, 6)); Assert.That(list1.IndexOf(node), Is.EqualTo(2)); Assert.That(list1.IndexOf(new RtfTreeNode()), Is.EqualTo(-1)); Assert.That(list1.IndexOf(node, 0), Is.EqualTo(2)); Assert.That(list1.IndexOf(node, 2), Is.EqualTo(2)); Assert.That(list1.IndexOf(node, 3), Is.EqualTo(4)); Assert.That(list1.IndexOf(node, 5), Is.EqualTo(-1)); Assert.That(list1.IndexOf("b", 0), Is.EqualTo(1)); Assert.That(list1.IndexOf("b", 1), Is.EqualTo(1)); Assert.That(list1.IndexOf("b", 2), Is.EqualTo(3)); Assert.That(list1.IndexOf("x", 0), Is.EqualTo(-1)); Assert.That(list1.IndexOf("b"), Is.EqualTo(1)); Assert.That(list1.IndexOf("x"), Is.EqualTo(-1)); }
/// <summary> /// Añadir o reemplazar el pie de página del documento /// </summary> /// <param name="footer">pie de página</param> public void SetFooter(RtfTreeNode footer) { RtfTreeNode footerGroup = null; // Find any existing footer RtfTreeNode existingFooter = this.mainGroup.SelectSingleNode("footer"); if (existingFooter != null) { // delete all child nodes of existing footer footerGroup = existingFooter.ParentNode; footerGroup.ChildNodes.Clear(); } else { // Insert a new footer group just before the body text int indInicioTexto = this.mainGroup.ChildNodes.IndexOf("pard"); footerGroup = new RtfTreeNode(RtfNodeType.Group); this.mainGroup.InsertChild(indInicioTexto, footerGroup); } footerGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "footer", false, 0)); if (footer != null) { footerGroup.AppendChild(footer); } }
/// <summary> /// Inserta el nuevo árbol en el árbol base (como un nuevo grupo) eliminando toda la cabecera del documento insertado. /// </summary> /// <param name="parentNode">Grupo base en el que se insertará el nuevo arbol.</param> /// <param name="treeToCopyParent">Nuevo árbol a insertar.</param> /// <param name="intCurrIndex">Índice en el que se insertará el nuevo árbol dentro del grupo base.</param> private void execMergeDoc(RtfTreeNode parentNode, RtfTree treeToCopyParent, int intCurrIndex) { //Se busca el primer "\pard" del documento (comienzo del texto) RtfTreeNode nodePard = treeToCopyParent.RootNode.FirstChild.SelectSingleChildNode("pard"); //Se obtiene el índice del nodo dentro del principal int indPard = treeToCopyParent.RootNode.FirstChild.ChildNodes.IndexOf(nodePard); //Se crea el nuevo grupo RtfTreeNode newGroup = new RtfTreeNode(RtfNodeType.Group); //Se resetean las opciones de párrafo y fuente newGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "pard", false, 0)); newGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "plain", false, 0)); //Se inserta cada nodo hijo del documento nuevo en el documento base for (int i = indPard + 1; i < treeToCopyParent.RootNode.FirstChild.ChildNodes.Count; i++) { RtfTreeNode newNode = treeToCopyParent.RootNode.FirstChild.ChildNodes[i].CloneNode(); newGroup.AppendChild(newNode); } //Se inserta el nuevo grupo con el nuevo documento parentNode.InsertChild(intCurrIndex, newGroup); }
public void TextExtraction() { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile("..\\..\\testdocs\\testdoc4.rtf"); RtfTreeNode simpleGroup = tree.MainGroup.SelectSingleGroup("ul"); RtfTreeNode nestedGroups = tree.MainGroup.SelectSingleGroup("cf"); RtfTreeNode keyword = tree.MainGroup.SelectSingleChildNode("b"); RtfTreeNode control = tree.MainGroup.SelectSingleChildNode("'"); RtfTreeNode root = tree.RootNode; Assert.That(simpleGroup.Text, Is.EqualTo("underline1")); Assert.That(nestedGroups.Text, Is.EqualTo("blue1 luctus. Fusce in interdum ipsum. Cum sociis natoque penatibus et italic1 dis parturient montes, nascetur ridiculus mus.")); Assert.That(keyword.Text, Is.EqualTo("")); Assert.That(control.Text, Is.EqualTo("é")); Assert.That(root.Text, Is.EqualTo("")); Assert.That(simpleGroup.RawText, Is.EqualTo("underline1")); Assert.That(nestedGroups.RawText, Is.EqualTo("blue1 luctus. Fusce in interdum ipsum. Cum sociis natoque penatibus et italic1 dis parturient montes, nascetur ridiculus mus.")); Assert.That(keyword.RawText, Is.EqualTo("")); Assert.That(control.RawText, Is.EqualTo("é")); Assert.That(root.RawText, Is.EqualTo("")); RtfTreeNode fontsGroup = tree.MainGroup.SelectSingleGroup("fonttbl"); RtfTreeNode generatorGroup = tree.MainGroup.SelectSingleGroup("*"); Assert.That(fontsGroup.Text, Is.EqualTo("")); Assert.That(generatorGroup.Text, Is.EqualTo("")); Assert.That(fontsGroup.RawText, Is.EqualTo("Times New Roman;Arial;Arial;")); Assert.That(generatorGroup.RawText, Is.EqualTo("Msftedit 5.41.15.1515;")); }
public void ResultNode() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf"); RtfTreeNode node = tree.MainGroup.SelectSingleNode("object").ParentNode; ObjectNode objNode = new ObjectNode(node); RtfTreeNode resNode = objNode.ResultNode; Assert.That(resNode, Is.SameAs(tree.MainGroup.SelectSingleGroup("object").SelectSingleChildGroup("result"))); RtfTreeNode pictNode = resNode.SelectSingleNode("pict").ParentNode; ImageNode imgNode = new ImageNode(pictNode); Assert.That(imgNode.Height, Is.EqualTo(2247)); Assert.That(imgNode.Width, Is.EqualTo(9320)); Assert.That(imgNode.DesiredHeight, Is.EqualTo(1274)); Assert.That(imgNode.DesiredWidth, Is.EqualTo(5284)); Assert.That(imgNode.ScaleX, Is.EqualTo(100)); Assert.That(imgNode.ScaleY, Is.EqualTo(100)); Assert.That(imgNode.ImageFormat, Is.EqualTo(ImageFormat.Emf)); }
/// <param name="node">Where to append (add) results</param> public static void AddText(this RtfTreeNode node, string text) { foreach (char c in text) { uint cCode = (uint)c; if (c == '\n') { node.AddKeyword("line"); } else if (cCode <= 225) { node.AddKeyword(String.Format("\'{0:X}", cCode)); } else if (cCode <= 32768) { node.AddKeyword("uc", 1); node.AddKeyword(String.Format("u{0}*", cCode)); } else if (cCode <= 65535) { node.AddKeyword("uc", 1); node.AddKeyword(String.Format("u{0}*", cCode - 65536)); } else { throw new NotSupportedException("Char code more than 16535 is not supported"); } } }
/// <summary> /// Devuelve el primer nodo del árbol, a partir del nodo actual, cuyo tipo es el indicado como parámetro. /// </summary> /// <param name="nodeType">Tipo del nodo buscado.</param> /// <returns>Primer nodo del árbol, a partir del nodo actual, cuyo tipo es el indicado como parámetro.</returns> public RtfTreeNode SelectSingleNode(RtfNodeType nodeType) { int i = 0; bool found = false; RtfTreeNode node = null; while (i < children.Count && !found) { if (children[i].type == nodeType) { node = children[i]; found = true; } else { node = children[i].SelectSingleNode(nodeType); if (node != null) { found = true; } } i++; } return(node); }
/// <summary> /// Obtiene los datos binarios del objeto a partir de la información contenida en el nodo RTF. /// </summary> private void getObjectData() { //Formato: ( '{' \object (<objtype> & <objmod>? & <objclass>? & <objname>? & <objtime>? & <objsize>? & <rsltmod>?) ('{\*' \objdata (<objalias>? & <objsect>?) <data> '}') <result> '}' ) string Text = ""; if (this.FirstChild.NodeKey == "object") { //Buscamos el nodo "\objdata" RtfTreeNode objdataNode = this.SelectSingleNode("objdata"); //Si existe el nodo if (objdataNode != null) { //Buscamos los datos en formato hexadecimal (último hijo del grupo de \objdata) Text = objdataNode.ParentNode.LastChild.NodeKey; int dataSize = Text.Length / 2; objdata = new byte[dataSize]; StringBuilder sbaux = new StringBuilder(2); for (int i = 0; i < Text.Length; i++) { sbaux.Append(Text[i]); if (sbaux.Length == 2) { objdata[i / 2] = byte.Parse(sbaux.ToString(), NumberStyles.HexNumber); sbaux.Remove(0, 2); } } } } }
/// <summary> /// Devuelve la tabla de fuentes del documento RTF. /// </summary> /// <returns>Tabla de fuentes del documento RTF</returns> public RtfFontTable GetFontTable() { RtfFontTable tablaFuentes = new RtfFontTable(); //Nodo raiz del documento RtfTreeNode root = rootNode; //Grupo principal del documento RtfTreeNode nprin = root.FirstChild; //Buscamos la tabla de fuentes en el árbol bool enc = false; int i = 0; RtfTreeNode ntf = new RtfTreeNode(); //Nodo con la tabla de fuentes while (!enc && i < nprin.ChildNodes.Count) { if (nprin.ChildNodes[i].NodeType == RtfNodeType.Group && nprin.ChildNodes[i].FirstChild.NodeKey == "fonttbl") { enc = true; ntf = nprin.ChildNodes[i]; } i++; } //Rellenamos el array de fuentes for (int j = 1; j < ntf.ChildNodes.Count; j++) { RtfTreeNode fuente = ntf.ChildNodes[j]; int indiceFuente = -1; string nombreFuente = null; int codePage = Encoding.Default.CodePage; foreach (RtfTreeNode nodo in fuente.ChildNodes) { if (nodo.NodeType == RtfNodeType.Keyword) { if (nodo.NodeKey == "f") { indiceFuente = nodo.Parameter; } else if (nodo.NodeKey == "fcharset") { codePage = CharSetConvertor.ToCodePage(nodo.Parameter, codePage); } } else if (nodo.NodeType == RtfNodeType.Text) { nombreFuente = nodo.NodeKey.Substring(0, nodo.NodeKey.Length - 1); } } tablaFuentes.AddFont(indiceFuente, new RtfFont(nombreFuente, codePage)); } return(tablaFuentes); }
/// <summary> /// Ajusta los colores del documento a insertar. /// </summary> /// <param name="parentNode">Nodo grupo que se está procesando.</param> /// <param name="colorDestTbl">Tabla de colores resultante.</param> /// <param name="colorToCopyTbl">Tabla de colores del documento a insertar.</param> private void adjustColorRecursive(RtfTreeNode parentNode, RtfColorTable colorDestTbl, RtfColorTable colorToCopyTbl) { if (parentNode != null && parentNode.HasChildNodes()) { for (int iNdIndex = 0; iNdIndex < parentNode.ChildNodes.Count; iNdIndex++) { if (parentNode.ChildNodes[iNdIndex].NodeType == RtfNodeType.Keyword && (parentNode.ChildNodes[iNdIndex].NodeKey == "cf" || parentNode.ChildNodes[iNdIndex].NodeKey == "cb" || parentNode.ChildNodes[iNdIndex].NodeKey == "pncf" || parentNode.ChildNodes[iNdIndex].NodeKey == "brdrcf" || parentNode.ChildNodes[iNdIndex].NodeKey == "cfpat" || parentNode.ChildNodes[iNdIndex].NodeKey == "cbpat" || parentNode.ChildNodes[iNdIndex].NodeKey == "clcfpatraw" || parentNode.ChildNodes[iNdIndex].NodeKey == "clcbpatraw" || parentNode.ChildNodes[iNdIndex].NodeKey == "ulc" || parentNode.ChildNodes[iNdIndex].NodeKey == "chcfpat" || parentNode.ChildNodes[iNdIndex].NodeKey == "chcbpat" || parentNode.ChildNodes[iNdIndex].NodeKey == "highlight" || parentNode.ChildNodes[iNdIndex].NodeKey == "clcbpat" || parentNode.ChildNodes[iNdIndex].NodeKey == "clcfpat") && parentNode.ChildNodes[iNdIndex].HasParameter) { parentNode.ChildNodes[iNdIndex].Parameter = baseRtfDoc.GetColorID(colorDestTbl, colorToCopyTbl[parentNode.ChildNodes[iNdIndex].Parameter]); } adjustColorRecursive(parentNode.ChildNodes[iNdIndex], colorDestTbl, colorToCopyTbl); } } }
public void SelectSiblings() { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile("..\\..\\testdocs\\testdoc1.rtf"); RtfTreeNode node1 = tree.MainGroup.ChildNodes[4]; //deflang3082 RtfTreeNode node2 = tree.MainGroup.ChildNodes[6].ChildNodes[2]; //colortbl/red RtfTreeNode n1 = node1.SelectSibling(RtfNodeType.Group); RtfTreeNode n2 = node1.SelectSibling("viewkind"); RtfTreeNode n3 = node1.SelectSibling("fs", 28); RtfTreeNode n4 = node2.SelectSibling(RtfNodeType.Keyword); RtfTreeNode n5 = node2.SelectSibling("blue"); RtfTreeNode n6 = node2.SelectSibling("red", 255); Assert.That(n1, Is.SameAs(tree.MainGroup[5])); Assert.That(n2, Is.SameAs(tree.MainGroup[8])); Assert.That(n3, Is.SameAs(tree.MainGroup[17])); Assert.That(n4, Is.SameAs(tree.MainGroup[6].ChildNodes[3])); Assert.That(n5, Is.SameAs(tree.MainGroup[6].ChildNodes[4])); Assert.That(n6, Is.SameAs(tree.MainGroup[6].ChildNodes[6])); }
/// <summary> /// Inserta un campo en el documento /// </summary> /// <param name="parent">Nodo padre del campo</param> /// <param name="instruction">El codigo de campo</param> /// <param name="initial_result">El valor del campo inicial</param> public void AddField(RtfTreeNode parent, string instruction, string initial_result) { var fieldInstructionGroup = new RtfTreeNode(RtfNodeType.Group); fieldInstructionGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "*", false, 0)); fieldInstructionGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "fldinst", false, 0)); var fieldInstructionTextGroup = new RtfTreeNode(RtfNodeType.Group); this.InsertText(fieldInstructionTextGroup, instruction); fieldInstructionGroup.AppendChild(fieldInstructionTextGroup); var fieldResultGroup = new RtfTreeNode(RtfNodeType.Group); fieldResultGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "fldrslt", false, 0)); var fieldResultTextGroup = new RtfTreeNode(RtfNodeType.Group); this.InsertText(fieldResultTextGroup, initial_result); fieldResultGroup.AppendChild(fieldResultTextGroup); var fieldGroup = new RtfTreeNode(RtfNodeType.Group); fieldGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "field", false, 0)); fieldGroup.AppendChild(fieldInstructionGroup); fieldGroup.AppendChild(fieldResultGroup); (parent ?? this.mainGroup).AppendChild(fieldGroup); }
public void StringRepresentation() { RtfTreeNode node = new RtfTreeNode(RtfNodeType.Keyword, "b", true, 3); RtfTreeNode node2 = new RtfTreeNode(RtfNodeType.Root); Assert.That(node.ToString(), Is.EqualTo("[Keyword, b, True, 3]")); Assert.That(node2.ToString(), Is.EqualTo("[Root, , False, 0]")); }
/// <summary> /// Elimina un nodo de la lista de hijos. /// </summary> /// <param name="node">Nodo a eliminar.</param> public void RemoveChild(RtfTreeNode node) { //Se busca el nodo a eliminar int index = children.IndexOf(node); //Se elimina el i-ésimo hijo children.RemoveAt(index); }
private void button6_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); //Se establecen las propiedades del cuadro de diálogo "Abrir" openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "Archivos RTF (*.rtf)|*.rtf|Todos los archivos (*.*)|*.*"; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true; //Se muestra el cuadro de diálogo Abrir y se espera a que se seleccione un fichero RTF. if (openFileDialog1.ShowDialog() == DialogResult.OK) { //Se crea un árbol RTF RtfTree arbol = new RtfTree(); //Se carga el documento seleccionado (Este método parsea el documento y crea la estructura de árbol interna) arbol.LoadRtfFile(openFileDialog1.FileName); //Busca el primer nodo de tipo objeto. RtfTreeNode node = arbol.RootNode.SelectSingleNode("object"); //Se crea un nodo RTF especializado en imágenes ObjectNode objectNode = new ObjectNode(node.ParentNode); //Se escriben al cuadro de texto superior algunos datos del objeto txtArbol.Text += "Object type: " + objectNode.ObjectType + "\r\n"; txtArbol.Text += "Object class: " + objectNode.ObjectClass + "\r\n"; //Se extrae la imagen insertada como representación del objeto //Se obtiene el nodo "\result" del objeto (representación externa del objeto en el documento RTF) RtfTreeNode resultNode = objectNode.ResultNode; RtfTreeNode auxNode = null; //Si existe un nodo imagen en el grupo "\result" la extraemos a un fichero y mostramos algunas características en //el cuadro de texto superior de la ventana. if ((auxNode = resultNode.SelectSingleNode("pict")) != null) { //Creamos el nodo especializado de tipo Imagen ImageNode imageNode = new ImageNode(auxNode.ParentNode); //Mostramos algunas características de la imagen 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"; //Se guarda la imagen a fichero MessageBox.Show("Se va a crear el fichero: image-example3." + getExtension(imageNode.ImageFormat)); imageNode.SaveImage("image-example3." + getExtension(imageNode.ImageFormat)); } else { MessageBox.Show("El grupo '\result' del objeto no contiene imágenes!"); } } }
public void Clear() { currentFormat = null; tree = new RtfTree(); mainGroup = new RtfTreeNode(RtfNodeType.Group); InitializeTree(); }
/// <summary> /// Constructor de la clase RtfTree. /// </summary> public RtfTree() { //Se crea el nodo raíz del documento rootNode = new RtfTreeNode(RtfNodeType.Root); /* Inicializados por defecto */ //Se inicializa la profundidad actual //level = 0; }
/// <summary> /// Devuelve la tabla de fuentes del documento RTF. /// </summary> /// <returns>Tabla de fuentes del documento RTF</returns> public String[] GetFontTable() { ArrayList tabla = new ArrayList(); String[] tablaFuentes; //Nodo raiz del documento RtfTreeNode root = this.rootNode; //Grupo principal del documento RtfTreeNode nprin = root.FirstChild; //Buscamos la tabla de fuentes en el árbol bool enc = false; int i = 0; RtfTreeNode ntf = new RtfTreeNode(); //Nodo con la tabla de fuentes while (!enc && i < nprin.ChildNodes.Count) { if (nprin.ChildNodes[i].NodeType == RtfNodeType.Group && nprin.ChildNodes[i].FirstChild.NodeKey == "fonttbl") { enc = true; ntf = nprin.ChildNodes[i]; } i++; } //Rellenamos el array de fuentes for (int j = 1; j < ntf.ChildNodes.Count; j++) { RtfTreeNode fuente = ntf.ChildNodes[j]; string nombreFuente = null; foreach (RtfTreeNode nodo in fuente.ChildNodes) { if (nodo.NodeType == RtfNodeType.Text) { nombreFuente = nodo.NodeKey.Substring(0, nodo.NodeKey.Length - 1); } } tabla.Add(nombreFuente); } //Convertimos el ArrayList en un array tradicional tablaFuentes = new String[tabla.Count]; for (int c = 0; c < tabla.Count; c++) { tablaFuentes[c] = (String)tabla[c]; } return(tablaFuentes); }
public static void ExtractDocumentOutline() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\test-doc.rtf"); RtfStyleSheetTable sst = tree.GetStyleSheetTable(); int heading1 = sst.IndexOf("heading 1"); int heading2 = sst.IndexOf("heading 2"); int heading3 = sst.IndexOf("heading 3"); tree.MainGroup.RemoveChild(tree.MainGroup.SelectChildGroups("stylesheet")[0]); RtfNodeCollection headingKeywords = tree.MainGroup.SelectNodes("s"); for (int i = 0; i < headingKeywords.Count; i++) { RtfTreeNode hk = headingKeywords[i]; StringBuilder text = new StringBuilder(""); if (hk.Parameter == heading1 || hk.Parameter == heading2 || hk.Parameter == heading3) { RtfTreeNode sibling = hk.NextSibling; while (sibling != null && !sibling.NodeKey.Equals("pard")) { if (sibling.NodeType == RtfNodeType.Text) { text.Append(sibling.NodeKey); } else if (sibling.NodeType == RtfNodeType.Group) { text.Append(ExtractGroupText(sibling)); } sibling = sibling.NextSibling; } if (hk.Parameter == heading1) { Console.WriteLine("H1: {0}", text); } else if (hk.Parameter == heading2) { Console.WriteLine(" H2: {0}", text); } else if (hk.Parameter == heading3) { Console.WriteLine(" H3: {0}", text); } } } }
/// <summary> /// Inserta un fragmento de texto en el documento con un formato de texto determinado. /// </summary> /// <param name="parent">Nodo padre del fragmento de texto</param> /// <param name="text">Texto a insertar.</param> /// <param name="format">Formato del texto a insertar.</param> /// <param name="highlight">Resaltar el texto?</param> public void AddText(RtfTreeNode parent, string text, RtfCharFormat format, bool highlight = false) { UpdateFontTable(format); UpdateColorTable(format); UpdateCharFormat(format); InsertText(parent, text, highlight); }
/// <summary> /// Inserta una imagen en el documento. /// </summary> /// <param name="path">Ruta de la imagen a insertar.</param> /// <param name="width">Ancho deseado de la imagen en el documento.</param> /// <param name="height">Alto deseado de la imagen en el documento.</param> public void AddImage(string path, int width, int height) { FileStream fStream = null; BinaryReader br = null; try { byte[] data = null; FileInfo fInfo = new FileInfo(path); long numBytes = fInfo.Length; fStream = new FileStream(path, FileMode.Open, FileAccess.Read); br = new BinaryReader(fStream); data = br.ReadBytes((int)numBytes); StringBuilder hexdata = new StringBuilder(); for (int i = 0; i < data.Length; i++) { hexdata.Append(GetHexa(data[i])); } Image img = Image.FromFile(path); RtfTreeNode imgGroup = new RtfTreeNode(RtfNodeType.Group); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "pict", false, 0)); string format = ""; if (path.ToLower().EndsWith("wmf")) { format = "emfblip"; } else { format = "jpegblip"; } imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, format, false, 0)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "picw", true, img.Width * 20)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "pich", true, img.Height * 20)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "picwgoal", true, width * 20)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "pichgoal", true, height * 20)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Text, hexdata.ToString(), false, 0)); mainGroup.AppendChild(imgGroup); } finally { br.Close(); fStream.Close(); } }
/// <summary> /// Inserta el código RTF de la aplicación generadora del documento. /// </summary> private void InsertGenerator() { RtfTreeNode genGroup = new RtfTreeNode(RtfNodeType.Group); genGroup.AppendChild(new RtfTreeNode(RtfNodeType.Control, "*", false, 0)); genGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "generator", false, 0)); genGroup.AppendChild(new RtfTreeNode(RtfNodeType.Text, "NRtfTree Library 1.3.0;", false, 0)); mainGroup.InsertChild(7, genGroup); }
public void SimpleTreeNavigation() { //Creación de un árbol sencillo RtfTree tree = new RtfTree(); RtfTreeNode mainGroup = new RtfTreeNode(RtfNodeType.Group); RtfTreeNode rtfNode = new RtfTreeNode(RtfNodeType.Keyword, "rtf", true, 0); mainGroup.AppendChild(rtfNode); RtfTreeNode newGroup = new RtfTreeNode(RtfNodeType.Group); RtfTreeNode node1 = new RtfTreeNode(RtfNodeType.Keyword, "ul", false, 0); RtfTreeNode node2 = new RtfTreeNode(RtfNodeType.Text, "Test", false, 0); RtfTreeNode node3 = new RtfTreeNode(RtfNodeType.Text, "ulnone", false, 0); newGroup.AppendChild(node1); newGroup.AppendChild(node2); newGroup.AppendChild(node3); mainGroup.AppendChild(newGroup); tree.RootNode.AppendChild(mainGroup); //Navegación básica: tree Assert.That(tree.RootNode, Is.Not.Null); Assert.That(tree.MainGroup, Is.SameAs(mainGroup)); //Navegación básica: newGroup Assert.That(newGroup.Tree, Is.SameAs(tree)); Assert.That(newGroup.ParentNode, Is.SameAs(mainGroup)); Assert.That(newGroup.RootNode, Is.SameAs(tree.RootNode)); Assert.That(newGroup.ChildNodes, Is.Not.Null); Assert.That(newGroup[1], Is.SameAs(node2)); Assert.That(newGroup.ChildNodes[1], Is.SameAs(node2)); Assert.That(newGroup["ul"], Is.SameAs(node1)); Assert.That(newGroup.FirstChild, Is.SameAs(node1)); Assert.That(newGroup.LastChild, Is.SameAs(node3)); Assert.That(newGroup.PreviousSibling, Is.SameAs(rtfNode)); Assert.That(newGroup.NextSibling, Is.Null); Assert.That(newGroup.Index, Is.EqualTo(1)); //Navegación básica: nodo2 Assert.That(node2.Tree, Is.SameAs(tree)); Assert.That(node2.ParentNode, Is.SameAs(newGroup)); Assert.That(node2.RootNode, Is.SameAs(tree.RootNode)); Assert.That(node2.ChildNodes, Is.Null); Assert.That(node2[1], Is.Null); Assert.That(node2["ul"], Is.Null); Assert.That(node2.FirstChild, Is.Null); Assert.That(node2.LastChild, Is.Null); Assert.That(node2.PreviousSibling, Is.SameAs(node1)); Assert.That(node2.NextSibling, Is.SameAs(node3)); Assert.That(node2.Index, Is.EqualTo(1)); }
/// <summary> /// Extrae el texto de un árbol RTF. /// </summary> /// <returns>Texto plano del documento.</returns> private string ConvertToText() { RtfTreeNode pardNode = this.RootNode.FirstChild.SelectSingleChildNode("pard"); int pPard = this.RootNode.FirstChild.ChildNodes.IndexOf(pardNode); Encoding enc = this.GetEncoding(); return(ConvertToTextAux(this.RootNode.FirstChild, pPard, enc)); }
public void SelectSingleChildNodeByKeywordAndParam() { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile("..\\..\\testdocs\\testdoc1.rtf"); RtfTreeNode node1 = tree.MainGroup.SelectSingleChildNode("fs", 24); RtfTreeNode node2 = tree.MainGroup.SelectSingleChildNode("f", 1); Assert.That(node1, Is.SameAs(tree.MainGroup[22])); Assert.That(node2, Is.SameAs(tree.MainGroup[56])); }
public void SelectSingleGroup() { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile("..\\..\\testdocs\\testdoc1.rtf"); RtfTreeNode node1 = tree.MainGroup.SelectSingleGroup("f"); RtfTreeNode node2 = tree.MainGroup[5].SelectSingleChildGroup("f"); Assert.That(node1, Is.SameAs(tree.MainGroup[5].ChildNodes[1])); Assert.That(node2, Is.SameAs(tree.MainGroup[5].ChildNodes[1])); }
public void EmptyNodeNavigation() { RtfTreeNode node = new RtfTreeNode(); Assert.That(node.Tree, Is.Null); Assert.That(node.RootNode, Is.Null); Assert.That(node.ParentNode, Is.Null); Assert.That(node.NextSibling, Is.Null); Assert.That(node.PreviousSibling, Is.Null); Assert.That(node.ChildNodes, Is.Null); Assert.That(node.FirstChild, Is.Null); Assert.That(node.LastChild, Is.Null); }
public void InitNodeNavigation() { RtfTreeNode node = new RtfTreeNode(RtfNodeType.Keyword, "rtf", true, 99); Assert.That(node.Tree, Is.Null); Assert.That(node.RootNode, Is.Null); Assert.That(node.ParentNode, Is.Null); Assert.That(node.NextSibling, Is.Null); Assert.That(node.PreviousSibling, Is.Null); Assert.That(node.ChildNodes, Is.Null); Assert.That(node.FirstChild, Is.Null); Assert.That(node.LastChild, Is.Null); }
public void PopulateCollection() { RtfNodeCollection list1 = new RtfNodeCollection(); RtfNodeCollection list2 = new RtfNodeCollection(); RtfTreeNode node = new RtfTreeNode(RtfNodeType.Keyword, "b", true, 2); list1.Add(new RtfTreeNode(RtfNodeType.Keyword, "a", true, 1)); list1.Add(node); list1.Add(new RtfTreeNode(RtfNodeType.Keyword, "c", true, 3)); list1.Add(new RtfTreeNode(RtfNodeType.Keyword, "d", true, 4)); list1.Add(new RtfTreeNode(RtfNodeType.Keyword, "e", true, 5)); list2.Add(node); list2.Add(new RtfTreeNode(RtfNodeType.Keyword, "g", true, 7)); Assert.That(list1.Count, Is.EqualTo(5)); Assert.That(list2.Count, Is.EqualTo(2)); Assert.That(list1[1], Is.SameAs(node)); Assert.That(list2[0], Is.SameAs(node)); list1.AddRange(list2); Assert.That(list1.Count, Is.EqualTo(7)); Assert.That(list1[5], Is.SameAs(list2[0])); Assert.That(list1[6], Is.SameAs(list2[1])); Assert.That(list1[6].NodeKey, Is.EqualTo("g")); Assert.That(list2[0], Is.SameAs(node)); RtfTreeNode node1 = new RtfTreeNode(RtfNodeType.Keyword, "h", false, 8); list1.Insert(5, node1); Assert.That(list1.Count, Is.EqualTo(8)); Assert.That(list1[5], Is.SameAs(node1)); RtfTreeNode node2 = new RtfTreeNode(RtfNodeType.Keyword, "i", false, 9); list1[1] = node2; Assert.That(list1.Count, Is.EqualTo(8)); Assert.That(list1[1], Is.SameAs(node2)); }
public void AdjacentNodes() { //Creación de un árbol sencillo RtfTree tree = new RtfTree(); RtfTreeNode mainGroup = new RtfTreeNode(RtfNodeType.Group); RtfTreeNode rtfNode = new RtfTreeNode(RtfNodeType.Keyword, "rtf", true, 0); mainGroup.AppendChild(rtfNode); RtfTreeNode newGroup = new RtfTreeNode(RtfNodeType.Group); RtfTreeNode node1 = new RtfTreeNode(RtfNodeType.Keyword, "ul", false, 0); RtfTreeNode node2 = new RtfTreeNode(RtfNodeType.Text, "Test", false, 0); RtfTreeNode node3 = new RtfTreeNode(RtfNodeType.Keyword, "ulnone", false, 0); newGroup.AppendChild(node1); newGroup.AppendChild(node2); newGroup.AppendChild(node3); mainGroup.AppendChild(newGroup); tree.RootNode.AppendChild(mainGroup); RtfTreeNode node4 = new RtfTreeNode(RtfNodeType.Text, "fin", false, 0); mainGroup.AppendChild(node4); Assert.That(tree.RootNode.NextNode, Is.SameAs(mainGroup)); Assert.That(mainGroup.NextNode, Is.SameAs(rtfNode)); Assert.That(rtfNode.NextNode, Is.SameAs(newGroup)); Assert.That(newGroup.NextNode, Is.SameAs(node1)); Assert.That(node1.NextNode, Is.SameAs(node2)); Assert.That(node2.NextNode, Is.SameAs(node3)); Assert.That(node3.NextNode, Is.SameAs(node4)); Assert.That(node4.NextNode, Is.Null); Assert.That(node4.PreviousNode, Is.SameAs(node3)); Assert.That(node3.PreviousNode, Is.SameAs(node2)); Assert.That(node2.PreviousNode, Is.SameAs(node1)); Assert.That(node1.PreviousNode, Is.SameAs(newGroup)); Assert.That(newGroup.PreviousNode, Is.SameAs(rtfNode)); Assert.That(rtfNode.PreviousNode, Is.SameAs(mainGroup)); Assert.That(mainGroup.PreviousNode, Is.SameAs(tree.RootNode)); Assert.That(tree.RootNode.PreviousNode, Is.Null); }
/// <summary> /// Constructor de la clase ImageNode. /// </summary> /// <param name="node">Nodo RTF del que se obtendrán los datos de la imagen.</param> public ImageNode(RtfTreeNode node) { if(node != null) { //Asignamos todos los campos del nodo NodeKey = node.NodeKey; HasParameter = node.HasParameter; Parameter = node.Parameter; ParentNode = node.ParentNode; RootNode = node.RootNode; NodeType = node.NodeType; ChildNodes = new RtfNodeCollection(); ChildNodes.AddRange(node.ChildNodes); //Obtenemos los datos de la imagen como un array de bytes getImageData(); } }
public void AddChildToEmptyNode() { RtfTreeNode node = new RtfTreeNode(); Assert.That(node.ChildNodes, Is.Null); RtfTreeNode childNode = new RtfTreeNode(); node.InsertChild(0, childNode); Assert.That(node.ChildNodes, Is.Not.Null); Assert.That(node.ChildNodes[0], Is.SameAs(childNode)); Assert.That(childNode.ChildNodes, Is.Null); RtfTreeNode anotherChildNode = new RtfTreeNode(); childNode.AppendChild(anotherChildNode); Assert.That(childNode.ChildNodes, Is.Not.Null); Assert.That(childNode.ChildNodes[0], Is.SameAs(anotherChildNode)); }
/// <summary> /// Constructor de la clase ObjectNode. /// </summary> /// <param name="node">Nodo RTF del que se obtendrán los datos de la imagen.</param> public ObjectNode(RtfTreeNode node) { if(node != null) { //Asignamos todos los campos del nodo this.NodeKey = node.NodeKey; this.HasParameter = node.HasParameter; this.Parameter= node.Parameter; this.ParentNode = node.ParentNode; this.RootNode = node.RootNode; this.NodeType = node.NodeType; this.ChildNodes.Clear(); this.ChildNodes.AddRange(node.ChildNodes); //Obtenemos los datos del objeto como un array de bytes getObjectData(); } }
/// <summary> /// Devuelve el índice del nodo pasado como parámetro dentro de la lista de nodos de la colección. /// </summary> /// <param name="node">Nodo a buscar en la colección.</param> /// <param name="startIndex">Posición dentro de la colección a partir del que se buscará.</param> /// <returns>Indice del nodo buscado. Devolverá el valor -1 en caso de no encontrarse el nodo dentro de la colección.</returns> public int IndexOf(RtfTreeNode node, int startIndex) { return InnerList.IndexOf(node, startIndex); }
/// <summary> /// Inserta un nuveo nodo en una posición determinada de la colección. /// </summary> /// <param name="index">Posición en la que insertar el nodo.</param> /// <param name="node">Nuevo nodo a insertar.</param> public void Insert(int index, RtfTreeNode node) { InnerList.Insert(index, node); }
/// <summary> /// Devuelve la tabla de colores del documento RTF. /// </summary> /// <returns>Tabla de colores del documento RTF</returns> public Color[] GetColorTable() { ArrayList tabla = new ArrayList(); Color[] tablaColores; //Nodo raiz del documento RtfTreeNode root = this.rootNode; //Grupo principal del documento RtfTreeNode nprin = root.FirstChild; //Buscamos la tabla de colores en el árbol bool enc = false; int i = 0; RtfTreeNode ntc = new RtfTreeNode(); //Nodo con la tabla de fuentes while (!enc && i < nprin.ChildNodes.Count) { if (nprin.ChildNodes[i].NodeType == RtfNodeType.Group && nprin.ChildNodes[i].FirstChild.NodeKey == "colortbl") { enc = true; ntc = nprin.ChildNodes[i]; } i++; } //Rellenamos el array de colores int rojo = 0; int verde = 0; int azul = 0; //Añadimos el color por defecto, en este caso el negro. //tabla.Add(Color.FromArgb(rojo,verde,azul)); for (int j = 1; j < ntc.ChildNodes.Count; j++) { RtfTreeNode nodo = ntc.ChildNodes[j]; if (nodo.NodeType == RtfNodeType.Text && nodo.NodeKey.Trim() == ";") { tabla.Add(Color.FromArgb(rojo, verde, azul)); rojo = 0; verde = 0; azul = 0; } else if (nodo.NodeType == RtfNodeType.Keyword) { switch (nodo.NodeKey) { case "red": rojo = nodo.Parameter; break; case "green": verde = nodo.Parameter; break; case "blue": azul = nodo.Parameter; break; } } } //Convertimos el ArrayList en un array tradicional tablaColores = new Color[tabla.Count]; for (int c = 0; c < tabla.Count; c++) { tablaColores[c] = (Color)tabla[c]; } return tablaColores; }
/// <summary> /// Analiza el documento y lo carga con estructura de árbol. /// </summary> /// <returns>Se devuelve el valor 0 en caso de no producirse ningún error en la carga del documento. /// En caso contrario se devuelve el valor -1.</returns> private int parseRtfTree() { //Resultado de la carga del documento int res = 0; //Codificación por defecto del documento Encoding encoding = Encoding.Default; //Nodo actual RtfTreeNode curNode = rootNode; //Nuevos nodos para construir el árbol RTF RtfTreeNode newNode = null; //Se obtiene el primer token tok = lex.NextToken(); while (tok.Type != RtfTokenType.Eof) { switch (tok.Type) { case RtfTokenType.GroupStart: newNode = new RtfTreeNode(RtfNodeType.Group,"GROUP",false,0); curNode.AppendChild(newNode); curNode = newNode; level++; break; case RtfTokenType.GroupEnd: curNode = curNode.ParentNode; level--; break; case RtfTokenType.Keyword: case RtfTokenType.Control: case RtfTokenType.Text: if (mergeSpecialCharacters) { //Contributed by Jan Stuchlík bool isText = tok.Type == RtfTokenType.Text || (tok.Type == RtfTokenType.Control && tok.Key == "'"); if (curNode.LastChild != null && (curNode.LastChild.NodeType == RtfNodeType.Text && isText)) { if (tok.Type == RtfTokenType.Text) { curNode.LastChild.NodeKey += tok.Key; break; } if (tok.Type == RtfTokenType.Control && tok.Key == "'") { curNode.LastChild.NodeKey += DecodeControlChar(tok.Parameter, encoding); break; } } else { //Primer caracter especial \' if (tok.Type == RtfTokenType.Control && tok.Key == "'") { newNode = new RtfTreeNode(RtfNodeType.Text, DecodeControlChar(tok.Parameter, encoding), false, 0); curNode.AppendChild(newNode); break; } } } newNode = new RtfTreeNode(tok); curNode.AppendChild(newNode); if (mergeSpecialCharacters) { //Contributed by Jan Stuchlík if (level == 1 && newNode.NodeType == RtfNodeType.Keyword && newNode.NodeKey == "ansicpg") { encoding = Encoding.GetEncoding(newNode.Parameter); } } break; default: res = -1; break; } //Se obtiene el siguiente token tok = lex.NextToken(); } //Si el nivel actual no es 0 ( == Algun grupo no está bien formado ) if (level != 0) { res = -1; } //Se devuelve el resultado de la carga return res; }
/// <summary> /// Método auxiliar para obtener el Texto RTF del nodo actual a partir de su representación en árbol. /// </summary> /// <param name="curNode">Nodo actual del árbol.</param> /// <param name="prevNode">Nodo anterior tratado.</param> /// <returns>Texto en formato RTF del nodo.</returns> private string getRtfInm(RtfTreeNode curNode, RtfTreeNode prevNode) { StringBuilder res = new StringBuilder(""); if (curNode.NodeType == RtfNodeType.Root) res.Append(""); else if (curNode.NodeType == RtfNodeType.Group) res.Append("{"); else { if (curNode.NodeType != RtfNodeType.Text) { res.Append("\\"); } else //curNode.NodeType == RtfNodeType.Text { if (prevNode == null || prevNode.NodeType == RtfNodeType.Control) { res.Append(""); } else //antNode.NodeType == RtfNodeType.KEYWORD { res.Append(" "); } } res.Append(curNode.NodeKey); if (curNode.HasParameter) { if (curNode.NodeType == RtfNodeType.Keyword) { res.Append(Convert.ToString(curNode.Parameter)); } else if (curNode.NodeType == RtfNodeType.Control) { //Si es un caracter especial como las vocales acentuadas if (curNode.NodeKey == "\'") { string hexa = Convert.ToString(curNode.Parameter, 16); if (hexa.Length == 1 ) { hexa = "0" + hexa; } res.Append(hexa); } } } } //Se obtienen los nodos hijos RtfNodeCollection children = curNode.ChildNodes; for (int i = 0; i < children.Count; i++) { RtfTreeNode node = children[i]; if (i > 0) res.Append(getRtfInm(node, children[i - 1])); else res.Append(getRtfInm(node, null)); if (node.NodeType == RtfNodeType.Group) { res.Append("}"); } } return res.ToString(); }
/// <summary> /// Añade un nuevo nodo a la colección actual. /// </summary> /// <param name="node">Nuevo nodo a añadir.</param> /// <returns>Posición en la que se ha insertado el nuevo nodo.</returns> public int Add(RtfTreeNode node) { InnerList.Add(node); return (InnerList.Count - 1); }
/// <summary> /// Inserta el código RTF de la tabla de fuentes en el documento. /// </summary> private void InsertFontTable() { RtfTreeNode ftGroup = new RtfTreeNode(RtfNodeType.Group); ftGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "fonttbl", false, 0)); for(int i=0; i<fontTable.Count; i++) { RtfTreeNode ftFont = new RtfTreeNode(RtfNodeType.Group); ftFont.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "f", true, i)); ftFont.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "fnil", false, 0)); ftFont.AppendChild(new RtfTreeNode(RtfNodeType.Text, fontTable[i] + ";", false, 0)); ftGroup.AppendChild(ftFont); } mainGroup.InsertChild(5, ftGroup); }
/// <summary> /// Realiza una copia exacta del nodo actual. /// </summary> /// <param name="cloneChildren">Si este parámetro recibe el valor true se clonarán también todos los nodos hijo del nodo actual.</param> /// <returns>Devuelve una copia exacta del nodo actual.</returns> public RtfTreeNode CloneNode(bool cloneChildren) { RtfTreeNode clon = new RtfTreeNode(); clon.key = this.key; clon.hasParam = this.hasParam; clon.param = this.param; clon.parent = this.parent; clon.root = this.root; clon.type = this.type; //Si cloneChildren=false se copia directamente la lista de hijos if (!cloneChildren) { clon.children = this.children; } else //En caso contrario se clonan también cada uno de los hijos, propagando el parámetro cloneChildren=true { clon.children = new RtfNodeCollection(); foreach (RtfTreeNode child in this.children) { clon.children.Add(child.CloneNode(true)); } } return clon; }
/// <summary> /// Extrae el texto de un nodo RTF (Auxiliar de ConvertToText()) /// </summary> /// <param name="curNode">Nodo actual.</param> /// <param name="prim">Nodo a partir del que convertir.</param> /// <param name="enc">Codificación del documento.</param> /// <returns>Texto plano del documento.</returns> private string ConvertToTextAux(RtfTreeNode curNode, int prim, Encoding enc) { StringBuilder res = new StringBuilder(""); RtfTreeNode nprin = curNode; RtfTreeNode nodo = new RtfTreeNode(); for (int i = prim; i < nprin.ChildNodes.Count; i++) { nodo = nprin.ChildNodes[i]; if (nodo.NodeType == RtfNodeType.Group) { res.Append(ConvertToTextAux(nodo, 0, enc)); } else if (nodo.NodeType == RtfNodeType.Control) { if (nodo.NodeKey == "'") res.Append(DecodeControlChar(nodo.Parameter, enc)); } else if (nodo.NodeType == RtfNodeType.Text) { res.Append(nodo.NodeKey); } else if (nodo.NodeType == RtfNodeType.Keyword) { if (nodo.NodeKey.Equals("par")) res.AppendLine(""); } } return res.ToString(); }
/// <summary> /// Constructor de la clase RtfDocument. /// </summary> /// <param name="path">Ruta del fichero a generar.</param> /// <param name="enc">Codificación del documento a generar.</param> public RtfDocument(string path, Encoding enc) { this.path = path; this.encoding = enc; fontTable = new RtfFontTable(); fontTable.AddFont("Arial"); //Default font colorTable = new RtfColorTable(); colorTable.AddColor(Color.Black); //Default color currentFormat = null; tree = new RtfTree(); mainGroup = new RtfTreeNode(RtfNodeType.Group); InitializeTree(); }
/// <summary> /// Constructor de la clase RtfTree. /// </summary> public RtfTree() { //Se crea el nodo raíz del documento rootNode = new RtfTreeNode(RtfNodeType.Root,"ROOT",false,0); rootNode.Tree = this; /* Inicializados por defecto */ //Se inicializa la propiedad mergeSpecialCharacters mergeSpecialCharacters = false; //Se inicializa la profundidad actual //level = 0; }
/// <summary> /// Devuelve la tabla de fuentes del documento RTF. /// </summary> /// <returns>Tabla de fuentes del documento RTF</returns> public String[] GetFontTable() { ArrayList tabla = new ArrayList(); String[] tablaFuentes; //Nodo raiz del documento RtfTreeNode root = this.rootNode; //Grupo principal del documento RtfTreeNode nprin = root.FirstChild; //Buscamos la tabla de fuentes en el árbol bool enc = false; int i = 0; RtfTreeNode ntf = new RtfTreeNode(); //Nodo con la tabla de fuentes while (!enc && i < nprin.ChildNodes.Count) { if (nprin.ChildNodes[i].NodeType == RtfNodeType.Group && nprin.ChildNodes[i].FirstChild.NodeKey == "fonttbl") { enc = true; ntf = nprin.ChildNodes[i]; } i++; } //Rellenamos el array de fuentes for (int j = 1; j < ntf.ChildNodes.Count; j++) { RtfTreeNode fuente = ntf.ChildNodes[j]; string nombreFuente = null; foreach (RtfTreeNode nodo in fuente.ChildNodes) { if (nodo.NodeType == RtfNodeType.Text) nombreFuente = nodo.NodeKey.Substring(0, nodo.NodeKey.Length - 1); } tabla.Add(nombreFuente); } //Convertimos el ArrayList en un array tradicional tablaFuentes = new String[tabla.Count]; for (int c = 0; c < tabla.Count; c++) { tablaFuentes[c] = (String)tabla[c]; } return tablaFuentes; }
/// <summary> /// Inserta el código RTF de la tabla de colores en el documento. /// </summary> private void InsertColorTable() { RtfTreeNode ctGroup = new RtfTreeNode(RtfNodeType.Group); ctGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "colortbl", false, 0)); for (int i = 0; i < colorTable.Count; i++) { ctGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "red", true, colorTable[i].R)); ctGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "green", true, colorTable[i].G)); ctGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "blue", true, colorTable[i].B)); ctGroup.AppendChild(new RtfTreeNode(RtfNodeType.Text, ";", false, 0)); } mainGroup.InsertChild(6, ctGroup); }
/// <summary> /// Devuelve el índice del nodo pasado como parámetro dentro de la lista de nodos de la colección. /// </summary> /// <param name="node">Nodo a buscar en la colección.</param> /// <returns>Indice del nodo buscado. Devolverá el valor -1 en caso de no encontrarse el nodo dentro de la colección.</returns> public int IndexOf(RtfTreeNode node) { return InnerList.IndexOf(node); }
/// <summary> /// Inserta una imagen en el documento. /// </summary> /// <param name="path">Ruta de la imagen a insertar.</param> /// <param name="width">Ancho deseado de la imagen en el documento.</param> /// <param name="height">Alto deseado de la imagen en el documento.</param> public void AddImage(string path, int width, int height) { FileStream fStream = null; BinaryReader br = null; try { byte[] data = null; FileInfo fInfo = new FileInfo(path); long numBytes = fInfo.Length; fStream = new FileStream(path, FileMode.Open, FileAccess.Read); br = new BinaryReader(fStream); data = br.ReadBytes((int)numBytes); StringBuilder hexdata = new StringBuilder(); for (int i = 0; i < data.Length; i++) { hexdata.Append(GetHexa(data[i])); } Image img = Image.FromFile(path); RtfTreeNode imgGroup = new RtfTreeNode(RtfNodeType.Group); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "pict", false, 0)); string format = ""; if (path.ToLower().EndsWith("wmf")) format = "emfblip"; else format = "jpegblip"; imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, format, false, 0)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "picw", true, img.Width * 20)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "pich", true, img.Height * 20)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "picwgoal", true, width * 20)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Keyword, "pichgoal", true, height * 20)); imgGroup.AppendChild(new RtfTreeNode(RtfNodeType.Text, hexdata.ToString(), false, 0)); mainGroup.AppendChild(imgGroup); } finally { br.Close(); fStream.Close(); } }
/// <summary> /// Método auxiliar para generar la representación Textual del documento RTF. /// </summary> /// <param name="curNode">Nodo actual del árbol.</param> /// <param name="level">Nivel actual en árbol.</param> /// <param name="showNodeTypes">Indica si se mostrará el tipo de cada nodo del árbol.</param> /// <returns>Representación Textual del nodo 'curNode' con nivel 'level'</returns> private string toStringInm(RtfTreeNode curNode, int level, bool showNodeTypes) { StringBuilder res = new StringBuilder(); RtfNodeCollection children = curNode.ChildNodes; for (int i = 0; i < level; i++) res.Append(" "); if (curNode.NodeType == RtfNodeType.Root) res.Append("ROOT\r\n"); else if (curNode.NodeType == RtfNodeType.Group) res.Append("GROUP\r\n"); else { if (showNodeTypes) { res.Append(curNode.NodeType); res.Append(": "); } res.Append(curNode.NodeKey); if (curNode.HasParameter) { res.Append(" "); res.Append(Convert.ToString(curNode.Parameter)); } res.Append("\r\n"); } foreach (RtfTreeNode node in children) { res.Append(toStringInm(node, level + 1, showNodeTypes)); } return res.ToString(); }
/// <summary> /// Parsea una fecha con formato "\yr2005\mo12\dy2\hr22\min56\sec15" /// </summary> /// <param name="group">Grupo RTF con la fecha.</param> /// <returns>Objeto DateTime con la fecha leida.</returns> private static DateTime parseDateTime(RtfTreeNode group) { DateTime dt; int year = 0, month = 0, day = 0, hour = 0, min = 0, sec = 0; foreach (RtfTreeNode node in group.ChildNodes) { switch (node.NodeKey) { case "yr": year = node.Parameter; break; case "mo": month = node.Parameter; break; case "dy": day = node.Parameter; break; case "hr": hour = node.Parameter; break; case "min": min = node.Parameter; break; case "sec": sec = node.Parameter; break; } } dt = new DateTime(year, month, day, hour, min, sec); return dt; }