【问题标题】:Extracting text from RTF with text and image从带有文本和图像的 RTF 中提取文本
【发布时间】:2022-01-18 14:11:51
【问题描述】:

我有一个从 WPF RichTextControl 中提取的字节数组,我从中提取文本。我成功使用了以下代码:

FlowDocument document = new FlowDocument();
TextRange txtRange = null;
using (MemoryStream stream = new MemoryStream(data))
{
    txtRange = new TextRange(document.ContentStart, document.ContentEnd);
    txtRange.Load(stream, DataFormats.XamlPackage);
}

当 rtf 中嵌入了图像时,问题就开始了。我仍然想提取文本,但上面的代码将在Load 方法上失败,并显示XamlParseException

我尝试使用以下方法:

using (RichTextBox rtb = new RichTextbox())
{
  rtb.Rtf = System.Text.Encoding.Default.GetString(data);
  // use rtb.Text
}

但 rtb.Rtf 的设置失败并显示 ArgumentException。原因可能是 explained here,因为 GetString 确实没有返回预期的 rtf 格式,而是将文本/二进制数据与 xaml 的提及混合在一起(同样的格式也仅返回文本,使用以前的方法成功提取)。我无法升级框架。

如果我能找到成功加载文档的方法,我不介意遍历 FlowDocument 树以提取文本。

是否有其他方法可以读取 RTF?

【问题讨论】:

    标签: c# xaml rtf


    【解决方案1】:

    显然,当图像包含在 RTF 中时,代码将在 STA 中运行时工作。例如:

    Thread t = new Thread(() => Foo(data));
    t.SetApartmentState(Apartment.STA);
    t.Start();
    t.Join();
    
    Foo()
    {
      FlowDocument document = new FlowDocument();
      TextRange txtRange = null;
      using (MemoryStream stream = new MemoryStream(data))
      {
          txtRange = new TextRange(document.ContentStart, document.ContentEnd);
          txtRange.Load(stream, DataFormats.XamlPackage);
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-10-17
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 2014-02-04
      • 2023-03-21
      • 2014-07-31
      相关资源
      最近更新 更多