using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace FastColoredTextBoxNS { /// /// Exports colored text as RTF /// /// At this time only TextStyle renderer is supported. Other styles is not exported. public class ExportToRTF { /// /// Includes line numbers /// public bool IncludeLineNumbers { get; set; } /// /// Use original font /// public bool UseOriginalFont { get; set; } FastColoredTextBox tb; Dictionary colorTable = new Dictionary(); public ExportToRTF() { UseOriginalFont = true; } public string GetRtf(FastColoredTextBox tb) { this.tb = tb; Range sel = new Range(tb); sel.SelectAll(); return GetRtf(sel); } public string GetRtf(Range r) { this.tb = r.tb; var styles = new Dictionary(); var sb = new StringBuilder(); var tempSB = new StringBuilder(); var currentStyleId = StyleIndex.None; r.Normalize(); int currentLine = r.Start.iLine; styles[currentStyleId] = null; colorTable.Clear(); // var lineNumberColor = GetColorTableNumber(r.tb.LineNumberColor); if (IncludeLineNumbers) tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", currentLine + 1, lineNumberColor); // foreach (Place p in r) { Char c = r.tb[p.iLine][p.iChar]; if (c.style != currentStyleId) { Flush(sb, tempSB, currentStyleId); currentStyleId = c.style; styles[currentStyleId] = null; } if (p.iLine != currentLine) { for (int i = currentLine; i < p.iLine; i++) { tempSB.AppendLine(@"\line"); if (IncludeLineNumbers) tempSB.AppendFormat(@"{{\cf{1} {0}}}\tab", i + 2, lineNumberColor); } currentLine = p.iLine; } switch (c.c) { case '\\': tempSB.Append(@"\\"); break; case '{': tempSB.Append(@"\{"); break; case '}': tempSB.Append(@"\}"); break; default: var ch = c.c; var code = (int)ch; if(code < 128) tempSB.Append(c.c); else tempSB.AppendFormat(@"{{\u{0}}}", code); break; } } Flush(sb, tempSB, currentStyleId); //build color table var list = new SortedList(); foreach (var pair in colorTable) list.Add(pair.Value, pair.Key); tempSB.Length = 0; tempSB.AppendFormat(@"{{\colortbl;"); foreach (var pair in list) tempSB.Append(GetColorAsString(pair.Value)+";"); tempSB.AppendLine("}"); // if (UseOriginalFont) { sb.Insert(0, string.Format(@"{{\fonttbl{{\f0\fmodern {0};}}}}{{\fs{1} ", tb.Font.Name, (int)(2 * tb.Font.SizeInPoints), tb.CharHeight)); sb.AppendLine(@"}"); } sb.Insert(0, tempSB.ToString()); sb.Insert(0, @"{\rtf1\ud\deff0"); sb.AppendLine(@"}"); return sb.ToString(); } private RTFStyleDescriptor GetRtfDescriptor(StyleIndex styleIndex) { List