C# 从 RTF 文本中获取纯文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/595865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get plain text from an RTF text
提问by rpf
I have on my database a column that holds text in RTF format.
我的数据库中有一个包含 RTF 格式文本的列。
How can I get only the plain text of it, using C#?
如何使用 C# 只获取它的纯文本?
Thanks :D
感谢:D
采纳答案by Daniel LeCheminant
Microsoft provides an examplewhere they basically stick the rtf text in a RichTextBoxand then read the .Textproperty... it feels somewhat kludgy, but it works.
微软提供了一个例子,他们基本上将 rtf 文本粘贴在 a 中RichTextBox,然后读取.Text属性......感觉有点笨拙,但它有效。
static public string ConvertToText(string rtf)
{
using(RichTextBox rtb = new RichTextBox())
{
rtb.Rtf = rtf;
return rtb.Text;
}
}
回答by Frank Krueger
If you want a pure code version, you can parse the rtf yourself and keep only the text bits. It's a bit of work, but not very difficult work - RTF files have a very simple syntax. Read about it in the RTF spec.
如果你想要一个纯代码版本,你可以自己解析 rtf 并只保留文本位。这是一些工作,但不是很困难的工作 - RTF 文件具有非常简单的语法。在 RTF 规范中阅读有关它的信息。
回答by Xavave
for WPF you can use (using Xceed WPF Toolkit) this extension method :
对于 WPF,您可以使用(使用 Xceed WPF Toolkit)这个扩展方法:
public static string RTFToPlainText(this string s)
{
// for information : default Xceed.Wpf.Toolkit.RichTextBox formatter is RtfFormatter
Xceed.Wpf.Toolkit.RichTextBox rtBox = new Xceed.Wpf.Toolkit.RichTextBox(new System.Windows.Documents.FlowDocument());
rtBox.Text = s;
rtBox.TextFormatter = new Xceed.Wpf.Toolkit.PlainTextFormatter();
return rtBox.Text;
}

