将RTF字符串转换为XAML字符串

时间:2014-09-30 14:54:51

标签: c# xaml rtf

在C#中将RTF字符串转换为XAML字符串的最有效方法是什么?我想使用System.Windows.Documents.XamlRtfConverter.ConvertRtfToXaml(string rtfContent),但不幸的是,该课程是内部的。

2 个答案:

答案 0 :(得分:5)

您可以从RTF字符串转到XAML字符串,但丢失图像:

 var rtf = File.ReadAllText(rtfFileName);
 var doc = new FlowDocument();
 var range = new TextRange(doc.ContentStart, doc.ContentEnd);
 using (var inputStream = new MemoryStream(Encoding.ASCII.GetBytes(rtf)))
 {
    range.Load(inputStream, DataFormats.Rtf);
    using (var outputStream = new MemoryStream())
    {
       range.Save(outputStream, DataFormats.Xaml);
       outputStream.Position = 0;
       using (var xamlStream = new StreamReader(outputStream))
       {
          var xaml = xamlStream.ReadToEnd();
          File.WriteAllText(xamlFileName, xaml);
       }
    }
 }

要保留图像,您必须从RTF字符串转到XAML包:

 var rtf = File.ReadAllText(rtfFileName);
 var doc = new FlowDocument();
 var range = new TextRange(doc.ContentStart, doc.ContentEnd);
 using (var inputStream = new MemoryStream(Encoding.ASCII.GetBytes(rtf)))
 {
    range.Load(inputStream, DataFormats.Rtf);
    using (var outputStream = new FileStream(xamlFileName, FileMode.Create))
    {
       range.Save(outputStream, DataFormats.XamlPackage);
    }
 }

答案 1 :(得分:2)

使用System.Reflection在System.Windows.Documents中调用内部方法XamlRtfConverter(需要引用PresentationFramework.dll)。 它适用于Parallel.ForEach()中的数千次转换,没有内存崩溃(与通过RichTextBox进行转换相反)。

    private static string ConvertRtfToXaml(string rtfContent)
    {
        var assembly = Assembly.GetAssembly(typeof(System.Windows.FrameworkElement));
        var xamlRtfConverterType = assembly.GetType("System.Windows.Documents.XamlRtfConverter");
        var xamlRtfConverter = Activator.CreateInstance(xamlRtfConverterType, true);
        var convertRtfToXaml = xamlRtfConverterType.GetMethod("ConvertRtfToXaml", BindingFlags.Instance | BindingFlags.NonPublic);
        var xamlContent = (string)convertRtfToXaml.Invoke(xamlRtfConverter, new object[] { rtfContent });
        return xamlContent;
    }