Extract RTF formatted text from WPF FlowDocument
Marius
1
Reputation point
Hello everybody,
I have a WPF FlowDocument which contains many Paragraphs. Each paragraph has a different LineHeight. Now, I want to save the FlowDocument as an RTF file using the code above but if there is a LineHeight property set for a paragraph, then it get lost, it's not saved. I've read somewhere that the DateFormats.Rtf leads to such behavior and it is recommanded to use DataFormats.Xaml instead, but I need the RTF formatted text.
public static string ToRtf(this string text)
{
var stringReader = new StringReader(text);
var xmlReader = XmlReader.Create(stringReader);
var sec = XamlReader.Load(xmlReader) as Section;
var doc = new FlowDocument();
foreach (var block in sec.Blocks.ToArray())
{
var fontFamily = block.FontFamily;
doc.Blocks.Add(block);
if (block.FontFamily != fontFamily) // because of unexpected reason the font get lost
block.FontFamily = fontFamily;
}
sec.Blocks.Clear();
using (var memoryStream = new MemoryStream())
{
new TextRange(doc.ContentStart, doc.ContentEnd).Save(memoryStream, DataFormats.Rtf);
return Encoding.Default.GetString(memoryStream.GetBuffer());
}
}
Is there a way to generate the RTF formatted text whitout loosing some properties?
Many thanks!