public void LoadImageDocFromFile() { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf"); //StreamWriter sw = null; //sw = new StreamWriter("testdocs\\rtf5.txt"); //sw.Write(tree.Rtf); //sw.Flush(); //sw.Close(); StreamReader sr = null; sr = new StreamReader("..\\..\\testdocs\\rtf5.txt"); string rtf5 = sr.ReadToEnd(); sr.Close(); sr = new StreamReader("..\\..\\testdocs\\text2.txt"); string text2 = sr.ReadToEnd(); sr.Close(); Assert.That(res, Is.EqualTo(0)); Assert.That(tree.MergeSpecialCharacters, Is.False); Assert.That(tree.Rtf, Is.EqualTo(rtf5)); Assert.That(tree.Text, Is.EqualTo(text2)); }
/// <summary> /// Constructor de la clase RtfMerger. /// </summary> /// <param name="templateTree">Ruta del documento plantilla.</param> public RtfMerger(RtfTree templateTree) { //Se carga el documento origen baseRtfDoc = templateTree; //Se crea la lista de parámetros de sustitución (placeholders) placeHolder = new Dictionary<string, RtfTree>(); }
public void EmptyTreeNavigation() { RtfTree tree = new RtfTree(); Assert.That(tree.RootNode, Is.Not.Null); Assert.That(tree.RootNode.Tree, Is.SameAs(tree)); Assert.That(tree.MainGroup, Is.Null); }
/// <summary> /// Constructor de la clase RtfMerger. /// </summary> /// <param name="templatePath">Ruta del documento plantilla.</param> public RtfMerger(string templatePath) { //Se carga el documento origen baseRtfDoc = new RtfTree(); baseRtfDoc.LoadRtfFile(templatePath); //Se crea la lista de parámetros de sustitución (placeholders) placeHolder = new Dictionary<string, RtfTree>(); }
public void ParseSimpleRtfText() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc1.rtf"); RtfPullParser parser = new RtfPullParser(); parser.LoadRtfText(tree.Rtf); parserTests(parser); }
/// <summary> /// Asocia un nuevo parámetro de sustitución (placeholder) con la ruta del documento a insertar. /// </summary> /// <param name="ph">Nombre del placeholder.</param> /// <param name="path">Ruta del documento a insertar.</param> public void AddPlaceHolder(string ph, string path) { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile(path); if (res == 0) { placeHolder.Add(ph, tree); } }
public void LoadObjectNode() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf"); RtfTreeNode node = tree.MainGroup.SelectSingleNode("object").ParentNode; ObjectNode objNode = new ObjectNode(node); Assert.That(objNode.ObjectType, Is.EqualTo("objemb")); Assert.That(objNode.ObjectClass, Is.EqualTo("Excel.Sheet.8")); }
public void ReplaceText() { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile("..\\..\\testdocs\\testdoc1.rtf"); tree.MainGroup.ReplaceText("Italic", "REPLACED"); StreamReader sr = null; sr = new StreamReader("..\\..\\testdocs\\rtf2.txt"); string rtf2 = sr.ReadToEnd(); sr.Close(); Assert.That(tree.Rtf, Is.EqualTo(rtf2)); }
/// <summary> /// Constructor de la clase RtfMerger. /// </summary> /// <param name="sSourceDocFullPathName">Ruta del documento plantilla.</param> /// <param name="sDestFileFullPathName">Ruta del documento resultante.</param> /// <param name="bolRemoveLastParCmd">Indica si se debe eliminar el último nodo \par de los documentos insertados en la plantilla.</param> public RtfMerger(string sSourceDocFullPathName, string sDestFileFullPathName, bool bolRemoveLastParCmd) { //Se carga el documento origen baseRtfDoc = new RtfTree(); baseRtfDoc.LoadRtfFile(sSourceDocFullPathName); //Se guarda la ruta del documento destino destFilePath = sDestFileFullPathName; //Indicativo de eliminación del último nodo \par para documentos insertados removeLastPar = bolRemoveLastParCmd; //Se crea la lista de parámetros de sustitución (placeholders) placeHolder = new Dictionary<string, RtfTree>(); }
public void FindText() { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile("..\\..\\testdocs\\testdoc1.rtf"); RtfNodeCollection list1 = tree.MainGroup.FindText("Italic"); Assert.That(list1.Count, Is.EqualTo(2)); Assert.That(list1[0], Is.SameAs(tree.MainGroup[18])); Assert.That(list1[0].NodeKey, Is.EqualTo("Bold Italic Underline Size 14")); Assert.That(list1[1], Is.SameAs(tree.MainGroup[73])); Assert.That(list1[1].NodeKey, Is.EqualTo("Italic2")); }
public void ImageBinData() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf"); RtfTreeNode pictNode = tree.MainGroup.SelectNodes("pict")[2].ParentNode; ImageNode imgNode = new ImageNode(pictNode); imgNode.SaveImage("..\\..\\testdocs\\img-result.png", ImageFormat.Jpeg); Stream fs1 = new FileStream("..\\..\\testdocs\\img-result.jpg", FileMode.Open); Stream fs2 = new FileStream("..\\..\\testdocs\\image1.jpg", FileMode.Open); Assert.That(fs1, Is.EqualTo(fs2)); }
public void ImageHexData() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf"); RtfTreeNode pictNode = tree.MainGroup.SelectNodes("pict")[2].ParentNode; ImageNode imgNode = new ImageNode(pictNode); StreamReader sr = null; sr = new StreamReader("..\\..\\testdocs\\imghexdata.txt"); string hexdata = sr.ReadToEnd(); sr.Close(); Assert.That(imgNode.HexData, Is.EqualTo(hexdata)); }
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); }
public void ObjectHexData() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf"); RtfTreeNode node = tree.MainGroup.SelectSingleNode("object").ParentNode; ObjectNode objNode = new ObjectNode(node); StreamReader sr = null; sr = new StreamReader("..\\..\\testdocs\\objhexdata.txt"); string hexdata = sr.ReadToEnd(); sr.Close(); Assert.That(objNode.HexData, Is.EqualTo(hexdata)); }
public static void ExtractDocumentProperties() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\test-doc.rtf"); InfoGroup info = tree.GetInfoGroup(); Console.WriteLine("Extracting document properties:"); Console.WriteLine("Title: {0}", info.Title); Console.WriteLine("Author: {0}", info.Author); Console.WriteLine("Company: {0}", info.Company); Console.WriteLine("Comments: {0}", info.DocComment); Console.WriteLine("Created: {0}", info.CreationTime); Console.WriteLine("Revised: {0}", info.RevisionTime); Console.WriteLine(""); }
private void button7_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); //Se obtiene la información del nodo "\info" InfoGroup info = arbol.GetInfoGroup(); //Si existe el nodo de información del documento if (info != null) { //Se muestran algunos datos del documento txtArbol.Text += "Title: " + info.Title + "\r\n"; txtArbol.Text += "Subject: " + info.Subject + "\r\n"; txtArbol.Text += "Author: " + info.Author + "\r\n"; txtArbol.Text += "Company: " + info.Company + "\r\n"; txtArbol.Text += "Category: " + info.Category + "\r\n"; txtArbol.Text += "Keywords: " + info.Keywords + "\r\n"; txtArbol.Text += "Comments: " + info.DocComment + "\r\n"; txtArbol.Text += "Creation Date: " + info.CreationTime + "\r\n"; txtArbol.Text += "Revision Date: " + info.RevisionTime + "\r\n"; txtArbol.Text += "Number of Pages: " + info.NumberOfPages + "\r\n"; txtArbol.Text += "Number of Words: " + info.NumberOfWords + "\r\n"; txtArbol.Text += "Number of Chars: " + info.NumberOfChars + "\r\n"; } } }
public void ObjectBinData() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf"); RtfTreeNode node = tree.MainGroup.SelectSingleNode("object").ParentNode; ObjectNode objNode = new ObjectNode(node); BinaryWriter bw = new BinaryWriter(new FileStream("..\\..\\testdocs\\objbindata-result.dat", FileMode.Create)); foreach (byte b in objNode.GetByteData()) bw.Write(b); bw.Close(); FileStream fs1 = new FileStream("..\\..\\testdocs\\objbindata-result.dat", FileMode.Open); FileStream fs2 = new FileStream("..\\..\\testdocs\\objbindata.dat", FileMode.Open); Assert.That(fs1, Is.EqualTo(fs2)); }
private string Convert() { var processLine = new RtfProcessLine(); var tree = new RtfTree(); tree.LoadRtfFile(m_FileName, Encoding.GetEncoding("Windows-1252")); m_Builder = new StringBuilder(); foreach (RtfTreeNode node in tree.MainGroup.ChildNodes) { switch (node.NodeType) { case RtfNodeType.Group: if (IncludeText(node.Text) && IsParaOpen) processLine.ProcessGroup(m_Builder, node, m_CurrentLine); break; case RtfNodeType.Text: if (IncludeText(node.Text) && IsParaOpen) processLine.AddText(m_Builder, node.Text); break; case RtfNodeType.Keyword: { switch (node.NodeKey) { case "line": case "par": if (IsParaOpen) m_Builder.AppendLine(); break; case "pard": StartNewPara(); break; case "tx": AddTabStop(node.Parameter); break; } break; } } } //Console.WriteLine("Document: " + m_Builder.ToString()); return m_Builder.ToString(); }
private static void ExtractObjects() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\test-doc.rtf"); //Busca el primer nodo de tipo objeto. RtfNodeCollection objects = tree.RootNode.SelectGroups("object"); Console.WriteLine("Extracting objects..."); int i = 1; foreach (RtfTreeNode node in objects) { //Se crea un nodo RTF especializado en imágenes ObjectNode objectNode = new ObjectNode(node); Console.WriteLine("Found new object:"); Console.WriteLine("Object type: " + objectNode.ObjectType); Console.WriteLine("Object class: " + objectNode.ObjectClass); byte[] data = objectNode.GetByteData(); FileStream binaryFile = new FileStream("..\\..\\testdocs\\object" + i + ".xls", FileMode.Create, FileAccess.ReadWrite); BinaryWriter bw = new BinaryWriter(binaryFile); for (int j = 38; j < data.Length; j++) { bw.Write(data[j]); } bw.Flush(); bw.Close(); Console.WriteLine("File 'object" + i + ".xls' created."); i++; } Console.WriteLine(""); }
public void LoadImageNode() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf"); RtfTreeNode pictNode = tree.MainGroup.SelectNodes("pict")[2].ParentNode; ImageNode imgNode = new ImageNode(pictNode); Assert.That(imgNode.Height, Is.EqualTo(6615)); Assert.That(imgNode.Width, Is.EqualTo(7938)); Assert.That(imgNode.DesiredHeight, Is.EqualTo(3750)); Assert.That(imgNode.DesiredWidth, Is.EqualTo(4500)); Assert.That(imgNode.ScaleX, Is.EqualTo(100)); Assert.That(imgNode.ScaleY, Is.EqualTo(100)); Assert.That(imgNode.ImageFormat, Is.EqualTo(ImageFormat.Png)); }
public void LoadSimpleDocMergeSpecialFromString() { RtfTree tree = new RtfTree(); tree.MergeSpecialCharacters = true; StreamReader sr = new StreamReader("..\\..\\testdocs\\testdoc1.rtf"); string strDoc = sr.ReadToEnd(); sr.Close(); int res = tree.LoadRtfText(strDoc); sr = new StreamReader("..\\..\\testdocs\\result1-3.txt"); string strTree1 = sr.ReadToEnd(); sr.Close(); sr = new StreamReader("..\\..\\testdocs\\result1-4.txt"); string strTree2 = sr.ReadToEnd(); sr.Close(); sr = new StreamReader("..\\..\\testdocs\\rtf1.txt"); string rtf1 = sr.ReadToEnd(); sr.Close(); sr = new StreamReader("..\\..\\testdocs\\text1.txt"); string text1 = sr.ReadToEnd(); sr.Close(); Assert.That(res, Is.EqualTo(0)); Assert.That(tree.MergeSpecialCharacters, Is.True); Assert.That(tree.ToString(), Is.EqualTo(strTree1)); Assert.That(tree.ToStringEx(), Is.EqualTo(strTree2)); Assert.That(tree.Rtf, Is.EqualTo(rtf1)); Assert.That(tree.Text, Is.EqualTo(text1)); }
public void SelectChildNodesByKeyword() { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile("..\\..\\testdocs\\testdoc1.rtf"); RtfNodeCollection lista1 = tree.MainGroup.SelectChildNodes("fs"); //5 nodes RtfNodeCollection lista2 = tree.MainGroup.SelectChildNodes("f"); //3 nodes Assert.That(lista1.Count, Is.EqualTo(5)); Assert.That(lista2.Count, Is.EqualTo(3)); Assert.That(lista1[0], Is.SameAs(tree.MainGroup[17])); Assert.That(lista1[1], Is.SameAs(tree.MainGroup[22])); Assert.That(lista1[2], Is.SameAs(tree.MainGroup[25])); Assert.That(lista1[3], Is.SameAs(tree.MainGroup[43])); Assert.That(lista1[4], Is.SameAs(tree.MainGroup[77])); Assert.That(lista2[0], Is.SameAs(tree.MainGroup[16])); Assert.That(lista2[1], Is.SameAs(tree.MainGroup[56])); Assert.That(lista2[2], Is.SameAs(tree.MainGroup[76])); }
private static void ConvertToHtml() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\test-doc2.rtf"); Rtf2Html rtfToHtml = new Rtf2Html(); Console.WriteLine("Processing..."); rtfToHtml.IncrustImages = false; string html = rtfToHtml.Convert(tree.Rtf); StreamWriter sw = new StreamWriter("..\\..\\testdocs\\test.html", false); sw.Write(html); sw.Flush(); sw.Close(); Console.WriteLine("File 'test.html' created."); Console.WriteLine(""); }
public void SelectSpecialGroups() { RtfTree tree = new RtfTree(); int res = tree.LoadRtfFile("..\\..\\testdocs\\testdoc1.rtf"); RtfNodeCollection list1 = tree.MainGroup.SelectChildGroups("generator"); RtfNodeCollection list2 = tree.MainGroup.SelectChildGroups("generator", false); RtfNodeCollection list3 = tree.MainGroup.SelectChildGroups("generator", true); RtfNodeCollection list4 = tree.MainGroup.SelectGroups("generator"); RtfNodeCollection list5 = tree.MainGroup.SelectGroups("generator", false); RtfNodeCollection list6 = tree.MainGroup.SelectGroups("generator", true); RtfTreeNode node1 = tree.MainGroup.SelectSingleChildGroup("generator"); RtfTreeNode node2 = tree.MainGroup.SelectSingleChildGroup("generator", false); RtfTreeNode node3 = tree.MainGroup.SelectSingleChildGroup("generator", true); RtfTreeNode node4 = tree.MainGroup.SelectSingleGroup("generator"); RtfTreeNode node5 = tree.MainGroup.SelectSingleGroup("generator", false); RtfTreeNode node6 = tree.MainGroup.SelectSingleGroup("generator", true); Assert.That(list1.Count, Is.EqualTo(0)); Assert.That(list2.Count, Is.EqualTo(0)); Assert.That(list3.Count, Is.EqualTo(1)); Assert.That(list4.Count, Is.EqualTo(0)); Assert.That(list5.Count, Is.EqualTo(0)); Assert.That(list6.Count, Is.EqualTo(1)); Assert.That(node1, Is.Null); Assert.That(node2, Is.Null); Assert.That(node3, Is.Not.Null); Assert.That(node4, Is.Null); Assert.That(node5, Is.Null); Assert.That(node6, Is.Not.Null); }
private void button1_Click(object sender, System.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 el árbol RTF. RtfTree arbol = new RtfTree(); //Se carga el documento seleccionado. arbol.LoadRtfFile(openFileDialog1.FileName); //Se muestra el árbol RTF extendido en el cuadro de texto superior de la ventana. txtArbol.Text = arbol.ToStringEx(); } }
public static void FormRTFDocument(string filename, ReportTable table) { RtfTree tree = new RtfTree(); string rtfBase = @"{\rtf1\ansi\deff0 {\fonttbl {\f0 Times New Roman;}}\fs24"; tree.LoadRtfText(rtfBase); //Load an RTF document from a file RtfTreeNode grp = new RtfTreeNode(RtfNodeType.Group); foreach (ReportRow row in table.Rows) { grp.AddTableRow(row.Cells); } tree.RootNode.FirstChild.AppendChild(grp); tree.SaveRtf(filename); //Get and print RTF code //Console.Write(tree.ToStringEx()); }
public void ObjectBinData() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc3.rtf"); RtfTreeNode node = tree.MainGroup.SelectSingleNode("object").ParentNode; ObjectNode objNode = new ObjectNode(node); BinaryWriter bw = new BinaryWriter(new FileStream("..\\..\\testdocs\\objbindata-result.dat", FileMode.Create)); foreach (byte b in objNode.GetByteData()) { bw.Write(b); } bw.Close(); FileStream fs1 = new FileStream("..\\..\\testdocs\\objbindata-result.dat", FileMode.Open); FileStream fs2 = new FileStream("..\\..\\testdocs\\objbindata.dat", FileMode.Open); Assert.That(fs1, Is.EqualTo(fs2)); }
private RtfTree _ConvertMMath(RtfTree tree) { RtfNodeCollection nodes = tree.RootNode.SelectNodes("mmath"); //RtfNodeCollection nodes = tree.RootNode.ChildNodes; foreach (RtfTreeNode n in nodes) { Console.WriteLine(n.ParentNode.Rtf); RtfTreeNode auxNode = null; if ((auxNode = n.ParentNode.SelectSingleNode("nonshppict")) != null) { ImageNode imageNode = new ImageNode(auxNode.ParentNode.SelectSingleNode("pict").ParentNode); ConvertEquation ce = new ConvertEquation(); EquationInput ei = new EquationInputFileEPS(imageNode.GetByteData()); EquationOutput eo = new EquationOutputFileGIF(GetOutputFile("gif")); ce.Convert(ei, eo); //string strEquation = ce.ConvertToText(ei); //EquationObj equationObj = Wmf2Equation(imageNode); //tree.RootNode.FirstChild.ReplaceChildDeep(n.ParentNode, getReplaceNode()); //rtf_replace.Add(equationObj); } else { MessageBox.Show("'\result' node contains no images!"); } tree.RootNode.FirstChild.RemoveChildDeep(n.ParentNode); } return(tree); }
private static void ConvertToHtml() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\test-doc2.rtf"); //tree.LoadRtfFile("..\\..\\testdocs\\test-doc4.rtf"); //several character set Rtf2Html rtfToHtml = new Rtf2Html(); Console.WriteLine("Processing..."); rtfToHtml.IncrustImages = false; string html = rtfToHtml.Convert(tree.Rtf); using (StreamWriter sw = new StreamWriter("..\\..\\testdocs\\test.html", false, Encoding.Default, 10000)) { sw.Write(html); sw.Flush(); sw.Close(); } Console.WriteLine("File 'test.html' created."); Console.WriteLine(""); }
private void button5_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 todos los nodos de tipo "\pict" (Imagen) RtfNodeCollection imageNodes = arbol.RootNode.SelectNodes("pict"); //Se recorren los nodos encontrados int i = 1; foreach (RtfTreeNode node in imageNodes) { //Se crea un nodo RTF especializado en imágenes ImageNode imageNode = new ImageNode(node.ParentNode); //Se guarda el contenido de la imagen a un fichero con el formato original con el que se almacenó en el documento. imageNode.SaveImage("image" + i + "." + getExtension(imageNode.ImageFormat)); i++; } } }
private RtfTree _ConvertObject(RtfTree tree) { RtfNodeCollection nodes = tree.RootNode.SelectNodes("object"); //RtfNodeCollection nodes = tree.RootNode.ChildNodes; foreach (RtfTreeNode n in nodes) { ObjectNode objectNode = new ObjectNode(n.ParentNode); if (objectNode.ObjectType == "objemb" && objectNode.ObjectClass == "Equation.DSMT4") { RtfTreeNode resultNode = objectNode.ResultNode; RtfTreeNode auxNode = null; if ((auxNode = resultNode.SelectSingleNode("pict")) != null) { ImageNode imageNode = new ImageNode(auxNode.ParentNode); EquationObj equationObj = Wmf2Equation(imageNode); tree.RootNode.FirstChild.ReplaceChildDeep(n.ParentNode, getReplaceNode()); rtf_replace.Add(equationObj); } else { MessageBox.Show("'\result' node contains no images!"); } } tree.RootNode.FirstChild.RemoveChildDeep(n.ParentNode); } return(tree); }
private RtfTree _ConvertPict(RtfTree tree) { RtfNodeCollection shppict_nodes = tree.RootNode.SelectNodes("shppict"); foreach (RtfTreeNode n in shppict_nodes) { tree.RootNode.FirstChild.RemoveChildDeep(n.ParentNode); } RtfNodeCollection pict_nodes = tree.RootNode.SelectNodes("pict"); foreach (RtfTreeNode n in pict_nodes) { ImageNode imageNode = new ImageNode(n.ParentNode); pictObj pictObj = new pictObj(); ImageConverter ic = new ImageConverter(); Image img = (Image)ic.ConvertFrom(imageNode.GetByteData()); ImageFormat format = getImageFormat(img); //string imgBase64Code = Convert.ToBase64String(imageNode.GetByteData()); string imgBase64Code = ImageToBase64(img, format); pictObj.format = format; pictObj.content = imgBase64Code; pictObj.attr("width", imageNode.Width); pictObj.attr("height", imageNode.Height); tree.RootNode.FirstChild.ReplaceChildDeep(n.ParentNode.ParentNode, getReplaceNode()); rtf_replace.Add(pictObj); tree.RootNode.FirstChild.RemoveChildDeep(n.ParentNode.ParentNode); } return(tree); }
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)); }
public void Clear() { currentFormat = null; tree = new RtfTree(); mainGroup = new RtfTreeNode(RtfNodeType.Group); InitializeTree(); }
/// <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> /// Convierte una cadena de código RTF a formato HTML /// </summary> public string Convert(string rtf) { //Console.WriteLine(rtf); //Generar arbol DOM RtfTree rtfTree = new RtfTree(); rtfTree.LoadRtfText(rtf); Console.WriteLine(rtfTree.ToStringEx()); //Inicializar variables empleadas _builder = new StringBuilder(); _htmlFormat = new Format(); this._builder.Append("<!DOCTYPE html><html><body> "); _formatList = new List <Format>(); _formatList.Add(new Format()); try { _fontTable = rtfTree.GetFontTable(); } catch { } try { _colorTable = rtfTree.GetColorTable(); } catch { } int inicio; for (inicio = 0; inicio < rtfTree.RootNode.FirstChild.ChildNodes.Count; inicio++) { if (rtfTree.RootNode.FirstChild.ChildNodes[inicio].NodeKey == "pard") { break; } } //Procesar todos los nodos visibles TransformChildNodes(rtfTree.RootNode.FirstChild.ChildNodes, inicio); ProcessChildNodes(rtfTree.RootNode.FirstChild.ChildNodes, inicio); //Cerrar etiquetas pendientes _formatList.Last().Reset(); WriteText(string.Empty); Regex repairList = new Regex("<span [^>]*>·</span><span style=\"([^\"]*)\">(.*?)<br\\s+/><" + "/span>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant); //foreach (Match match in repairList.Matches(_builder.ToString())) //{ // _builder.Replace(match.Value, string.Format("<li style=\"{0}\">{1}</li>", match.Groups[1].Value, match.Groups[2].Value)); //} //Regex repairUl = new Regex("(?<!</li>)<li", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); //foreach (Match match in repairUl.Matches(_builder.ToString())) //{ // _builder.Insert(match.Index, "<ul>"); //} //repairUl = new Regex("/li>(?!<li)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); //foreach (Match match in repairUl.Matches(_builder.ToString())) //{ // _builder.Insert(match.Index + match.Length, "</ul>"); //} if (AutoParagraph) { string[] partes = _builder.ToString().Split(new[] { "<br /><br />" }, StringSplitOptions.RemoveEmptyEntries); _builder = new StringBuilder(_builder.Length + 7 * partes.Length); foreach (string parte in partes) { _builder.Append("<p>"); _builder.Append(parte); _builder.Append("</p>"); } } this._builder.Append("</body></html>"); //Console.WriteLine(_builder.ToString()); return(EscapeHtmlEntities ? HtmlEntities.Encode(_builder.ToString()) : _builder.ToString()); }
/// <summary> /// Inserta un nuevo árbol en el lugar de una etiqueta de texto del árbol base. /// </summary> /// <param name="parentNode">Nodo de tipo grupo que se está procesando.</param> /// <param name="iNdIndex">Índice (dentro del grupo padre) del nodo texto que se está procesando.</param> /// <param name="docToInsert">Nuevo árbol RTF a insertar.</param> /// <param name="strCompletePlaceholder">Texto del la etiqueta que se va a reemplazar.</param> /// <param name="intPlaceHolderNodePos">Posición de la etiqueta que se va a reemplazar dentro del nodo texto que se está procesando.</param> private void mergeCore(RtfTreeNode parentNode, int iNdIndex, RtfTree docToInsert, string strCompletePlaceholder, int intPlaceHolderNodePos) { //Si el documento a insertar no está vacío if (docToInsert.RootNode.HasChildNodes() == true) { int currentIndex = iNdIndex + 1; //Se combinan las tablas de colores y se ajustan los colores del documento a insertar mainAdjustColor(docToInsert); //Se combinan las tablas de fuentes y se ajustan las fuentes del documento a insertar mainAdjustFont(docToInsert); //Se elimina la información de cabecera del documento a insertar (colores, fuentes, info, ...) cleanToInsertDoc(docToInsert); //Si el documento a insertar tiene contenido if (docToInsert.RootNode.FirstChild.HasChildNodes()) { //Se inserta el documento nuevo en el árbol base execMergeDoc(parentNode, docToInsert, currentIndex); } //Si la etiqueta no está al final del nodo texto: //Se inserta un nodo de texto con el resto del texto original (eliminando la etiqueta) if (parentNode.ChildNodes[iNdIndex].NodeKey.Length != (intPlaceHolderNodePos + strCompletePlaceholder.Length)) { //Se inserta un nodo de texto con el resto del texto original (eliminando la etiqueta) string remText = parentNode.ChildNodes[iNdIndex].NodeKey.Substring( parentNode.ChildNodes[iNdIndex].NodeKey.IndexOf(strCompletePlaceholder) + strCompletePlaceholder.Length); parentNode.InsertChild(currentIndex + 1, new RtfTreeNode(RtfNodeType.Text, remText, false, 0)); } //Si la etiqueta reemplazada estaba al principio del nodo de texto eliminamos el nodo //original porque ya no es necesario if (intPlaceHolderNodePos == 0) { parentNode.RemoveChild(iNdIndex); } //En otro caso lo sustituimos por el texto previo a la etiqueta else { parentNode.ChildNodes[iNdIndex].NodeKey = parentNode.ChildNodes[iNdIndex].NodeKey.Substring(0, intPlaceHolderNodePos); } } }
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)); }
/// <summary> /// Elimina los elementos no deseados del documento a insertar, por ejemplo los nodos "\par" finales. /// </summary> /// <param name="docToInsert">Documento a insertar.</param> private void cleanToInsertDoc(RtfTree docToInsert) { //Borra el último "\par" del documento si existe RtfTreeNode lastNode = docToInsert.RootNode.FirstChild.LastChild; if (removeLastPar) { if (lastNode.NodeType == RtfNodeType.Keyword && lastNode.NodeKey == "par") { docToInsert.RootNode.FirstChild.RemoveChild(lastNode); } } }
/// <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(true); newGroup.AppendChild(newNode); } //Se inserta el nuevo grupo con el nuevo documento parentNode.InsertChild(intCurrIndex, newGroup); }
/// <summary> /// Ajusta los colores del documento a insertar. /// </summary> /// <param name="docToInsert">Documento a insertar.</param> private void mainAdjustColor(RtfTree docToInsert) { RtfColorTable colorDestTbl = baseRtfDoc.GetColorTable(); RtfColorTable colorToCopyTbl = docToInsert.GetColorTable(); adjustColorRecursive(docToInsert.RootNode, colorDestTbl, colorToCopyTbl); }
/// <summary> /// Asocia un nuevo parámetro de sustitución (placeholder) con la ruta del documento a insertar. /// </summary> /// <param name="ph">Nombre del placeholder.</param> /// <param name="docTree">Árbol RTF del documento a insertar.</param> public void AddPlaceHolder(string ph, RtfTree docTree) { placeHolder.Add(ph, docTree); }
/// <summary> /// Guarda el documento como fichero RTF en la ruta indicada. /// </summary> /// <param name="path">Ruta del fichero a crear.</param> public void Save(string path) { RtfTree tree = GetTree(); tree.SaveRtf(path); }
public void InitTestFixture() { tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\testdoc2.rtf"); }
private static void ExtractImages() { RtfTree tree = new RtfTree(); tree.LoadRtfFile("..\\..\\testdocs\\test-doc.rtf"); RtfNodeCollection imageNodes = tree.RootNode.SelectNodes("pict"); Console.WriteLine("Extracting images..."); int i = 1; foreach (RtfTreeNode node in imageNodes) { ImageNode imageNode = new ImageNode(node.ParentNode); if (imageNode.ImageFormat == ImageFormat.Png) { imageNode.SaveImage("..\\..\\testdocs\\image" + i + ".png"); Console.WriteLine("File '" + "image" + i + ".png" + "' created."); i++; } } Console.WriteLine(""); }
/// <summary> /// Ajusta las fuentes del documento a insertar. /// </summary> /// <param name="docToInsert">Documento a insertar.</param> private void mainAdjustFont(RtfTree docToInsert) { RtfFontTable fontDestTbl = baseRtfDoc.GetFontTable(); RtfFontTable fontToCopyTbl = docToInsert.GetFontTable(); adjustFontRecursive(docToInsert.RootNode, fontDestTbl, fontToCopyTbl); }
/// <summary> /// Realiza una copia exacta del árbol RTF. /// </summary> /// <returns>Devuelve una copia exacta del árbol RTF.</returns> public RtfTree CloneTree() { RtfTree clon = new RtfTree(); clon.rootNode = rootNode.CloneNode(); return clon; }
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> /// Convierte una cadena de código RTF a formato HTML /// </summary> public string Convert(string rtf) { //Generar arbol DOM RtfTree rtfTree = new RtfTree(); rtfTree.LoadRtfText(rtf); //Inicializar variables empleadas _builder = new StringBuilder(); _htmlFormat = new Format(); _currentFormat = new Format(); _fontTable = rtfTree.GetFontTable(); _colorTable = rtfTree.GetColorTable(); //Buscar el inicio del contenido visible del documento int inicio; for (inicio = 0; inicio < rtfTree.RootNode.FirstChild.ChildNodes.Count; inicio++) { if (rtfTree.RootNode.FirstChild.ChildNodes[inicio].NodeKey == "pard") { break; } } //Procesar todos los nodos visibles ProcessChildNodes(rtfTree.RootNode.FirstChild.ChildNodes, inicio); //Cerrar etiquetas pendientes _currentFormat.Reset(); WriteText(string.Empty); //Arreglar HTML //Arreglar listas Regex repairList = new Regex("<span [^>]*>·</span><span style=\"([^\"]*)\">(.*?)<br\\s+/><" + "/span>", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.CultureInvariant); foreach (Match match in repairList.Matches(_builder.ToString())) { _builder.Replace(match.Value, string.Format("<li style=\"{0}\">{1}</li>", match.Groups[1].Value, match.Groups[2].Value)); } Regex repairUl = new Regex("(?<!</li>)<li", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); foreach (Match match in repairUl.Matches(_builder.ToString())) { _builder.Insert(match.Index, "<ul>"); } repairUl = new Regex("/li>(?!<li)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); foreach (Match match in repairUl.Matches(_builder.ToString())) { _builder.Insert(match.Index + match.Length, "</ul>"); } //Generar párrafos (cada 2 <br /><br /> se cambiará por un <p>) if (AutoParagraph) { string[] partes = _builder.ToString().Split(new[] { "<br /><br />" }, StringSplitOptions.RemoveEmptyEntries); _builder = new StringBuilder(_builder.Length + 7 * partes.Length); foreach (string parte in partes) { _builder.Append("<p>"); _builder.Append(parte); _builder.Append("</p>"); } } return(EscapeHtmlEntities ? HtmlEntities.Encode(_builder.ToString()) : _builder.ToString()); }
public static void CheckAttachmentsForDocOrPDFText(ActiveRecord record) { //walk the field list for this record looking for attachments foreach (var fieldName in record.GetFieldNames()) { if (fieldName.Contains("Attachment") && fieldName.DoesntContain("RawText")) { //if (record.Fields.Attachment.IsDirty) { if (ActiveFieldBase.IsDirtyObj(record[fieldName].ValueObject, record[fieldName].OriginalValueObject)) { if (record[fieldName].ToString().Contains(".doc") || record[fieldName].ToString().EndsWith(".pdf") || record[fieldName].ToString().EndsWith(".rtf")) { if (!record.FieldExists(fieldName + "RawText")) { (new Sql("ALTER TABLE ", record.GetTableName().SqlizeName(), " ADD [" + fieldName + "RawText] nvarchar (MAX);")).Execute(); } string output = ""; if (record[fieldName].ToString().ToLower().EndsWith(".doc")) { OfficeFileReader.OfficeFileReader objOFR = new OfficeFileReader.OfficeFileReader(); if (objOFR.GetText(Web.MapPath(Web.Attachments) + record[fieldName].ToString(), ref output) > 0) { //ok } } else if (record[fieldName].ToString().ToLower().EndsWith(".docx")) { BewebCore.ThirdParty.ReadWordDocText.DocxToText objOFR = new DocxToText(Web.MapPath(Web.Attachments) + record[fieldName].ToString()); if ((output = objOFR.ExtractText()).Length > 0) { //ok } } else if (record[fieldName].ToString().Contains(".pdf")) { PdfToText.PDFParser pdf = new PDFParser(); if (pdf.ExtractText(Web.MapPath(Web.Attachments) + record[fieldName].ToString(), ref output)) { //ok } } else if (record[fieldName].ToString().Contains(".rtf")) { #if RTFProcessingAvailable //Create the RTF tree object RtfTree tree = new RtfTree(); //Load and parse RTF document tree.LoadRtfFile(Web.MapPath(Web.Attachments) + record[fieldName].ToString()); output = tree.Text; #else throw new Exception("rtf library not included"); #endif } if (output.Trim() != "") { (new Sql("update ", record.GetTableName().SqlizeName(), "set " + fieldName + "RawText=", output.SqlizeText(), " where ", record.GetPrimaryKeyName().SqlizeName(), "=", record.ID_Field.Sqlize(), "")).Execute(); } } else { //no doc any more if (record.FieldExists(fieldName + "RawText")) { (new Sql("update ", record.GetTableName().SqlizeName(), "set " + fieldName + "RawText=null where ", record.GetPrimaryKeyName().SqlizeName(), "=", record.ID_Field.Sqlize(), "")).Execute(); } } } } } }