How to convert FlowDocument to rtf

17,895

Solution 1

You should not persist the FlowDocument directly as it should be considered the runtime representation of the document, not the actual document content. Instead, use the TextRange class to Save and Load to various formats including Rtf.

A quick sample on how to create a selection and save to a stream:

var content = new TextRange(doc.ContentStart, doc.ContentEnd);

if (content.CanSave(DataFormats.Rtf))
{
    using (var stream = new MemoryStream())
    {
        content.Save(stream, DataFormats.Rtf);
    }
}

To load content into a selection would be similar:

var content = new TextRange(doc.ContentStart, doc.ContentEnd);

if (content.CanLoad(DataFormats.Rtf))
{
    content.Load(stream, DataFormats.Rtf);
}

Solution 2

This works like a charm for me. Displays the result in an RTF box without difficulties.

public static string getDocumentAsXaml(IDocumentPaginatorSource flowDocument)
{
     return XamlWriter.Save(flowDocument);
}
Share:
17,895
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I have used a WPF RichTextBox to save a flowdocument from it as byte[] in database. Now i need to retrieve this data and display in a report RichTextBox as an rtf. when i try to convert the byte[] using TextRange or in XAMLReader i get a FlowDocument back but how do i convert it to rtf string as the report RichTextBox only takes rtf.

    Thanks

    Arvind

  • Admin
    Admin about 15 years
    Thanks for your responce but i have tryed this method and this this does not save the formating made in the text(ie making text bold changing colour),i need to also the save the format so i save it as a flowDodcument
  • BrainSlugs83
    BrainSlugs83 over 10 years
    He doesn't address the problem. The code just reads an RTF string from a binary database field (as ASCII >.<), and then loads it into a flow document as RTF.
  • user1359009
    user1359009 about 10 years
    Accepted Answer: use the TextRange class to Save and Load to various formats including Rtf.
  • user1359009
    user1359009 about 10 years
    The solution offered here uses textrange to load memorystream, DataFormats.RTF ... same as accepted ... just displayed a field grab ... you guys troll much >.<