C#操作.rtf文档

前段时间做过一些用C#操作.rtf文档的工作,当时就是直接根据RTF的规范用修改文本文件的方式修改.rtf文件。比如要插入一段文字,并且用红色表示,就自己弄一个colortable的定义,然后直接把下面的内容插入到.rtf文件中, {\b\cf1Bold Red!} \b表示黑体,\cf1表示用colortable定义中的第一种颜色。(假设我们的这个rtf文件中定义的第一种颜色是红色)。但是这种办法很不直观,而且有限制,需要编码时知道colortable是怎么定义的。

今天重新用System.Windows.Forms.RichTextBox来实现。下面的代码实现了在原来的rtf文件的最开始插入一行红色黑体的“Alert”,然后在rtf的commens:后面加上“new comment”,最后在末尾加一句“Bye!”。

    1         private static void RtfTest(string inpath, string outpath)

    2         {

    3             // load rtf file

    4             RichTextBox rtf = new RichTextBox();

    5             using (StreamReader sr = new StreamReader(inpath))

    6             {

    7                 rtf.Rtf = sr.ReadToEnd();

    8             }

    9 

   10             // add alert the begining of the rtf file

   11             rtf.SelectionStart = 0;

   12             rtf.SelectionLength = 1;

   13             string alert = "Alert!" + Environment.NewLine;

   14             rtf.SelectedText = alert + rtf.SelectedText;

   15             rtf.SelectionStart = 0;

   16             // length of new line in string is 2, but in rtf is 1, so we need to minus the line count

   17             rtf.SelectionLength = alert.Length - 1;

   18             rtf.SelectionColor = Color.Red;

   19             rtf.SelectionFont = new Font(rtf.SelectionFont, System.Drawing.FontStyle.Bold);

   20 

   21 

   22             // add comment after "Comments:"

   23             string commentStart = "Comments:";

   24             string newComment = "new comment";

   25             rtf.Find(commentStart);

   26             rtf.SelectedText = rtf.SelectedText + Environment.NewLine + newComment;

   27             rtf.Find(commentStart);

   28             rtf.SelectionStart += commentStart.Length;

   29             rtf.SelectionLength += newComment.Length;

   30             rtf.SelectionColor = Color.Black;

   31             rtf.SelectionFont = new Font(rtf.SelectionFont, System.Drawing.FontStyle.Regular);

   32 

   33             // add "Bye!" to the end

   34             rtf.AppendText(Environment.NewLine + "Bye!");

   35 

   36             // save the rtf file

   37             rtf.SaveFile(outpath);

   38             rtf.Dispose();

   39             rtf = null;

   40         }



其中有几个需要注意的地方:
1.不能直接给rtf.Text赋值,给Text赋值会导致整个rtf文档的格式丢失。这个示例中使用了selection来实现。
2.string中的换行的length是2,但是rtf中的换行的length是1,根据这个长度设置选择区域是要注意。
3.往rtf文档的最后以行加东西可以直接调用AppendText,会保留原来的格式。


posted on 2010-12-16 18:04  fresky  阅读(3212)  评论(0编辑  收藏  举报

导航