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

本文关键字:字符串 XAML 转换 RTF | 更新日期: 2023-09-27 18:25:02

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

将RTF字符串转换为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 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);
    }
 }

使用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;
    }