What is the most efficient way to convert an RTF string to a XAML string in C#? I'd like to use System.Windows.Documents.XamlRtfConverter.ConvertRtfToXaml(string rtfContent)
but unfortunately that class is internal.
Convert RTF string to XAML string
You can go from an RTF string to a XAML string but you lose images:
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);
}
}
}
To preserve images you have to go from an RTF string to a XAML package:
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);
}
}
Use System.Reflection to invoke internal method XamlRtfConverter in System.Windows.Documents (needs reference to PresentationFramework.dll). It works for thousands of conversions in Parallel.ForEach() without memory crashes (in contrast to conversion via 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;
}
© 2022 - 2024 — McMap. All rights reserved.
Xaml string
? – ChagresXAML string
related toRTF string
is strange to me... – Chagres