C#操作.rtf文档
今天重新用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,会保留原来的格式。