Partilhar via


Saving, loading, printing RichContent in WPF

Saving, loading and printing RichTextBox contents is a pretty common scenario and I just thought it would be a good idea to have some code out for general reading :). Most of the code below is self explanatory - so I wont go about explaining it.

The code below saves the content in XamlPackage format which is the most rich content produced by RichTextBox. This is followed by Xaml and then rtf.

 void SaveXamlPackage(string _fileName){   TextRange range;   FileStream fStream;   range = new TextRange(RTB.Document.ContentStart, RTB.Document.ContentEnd);   fStream = new FileStream(_fileName, FileMode.Create);   range.Save(fStream, DataFormats.XamlPackage);   fStream.Close();} void LoadXamlPackage(string _fileName){   TextRange range;   FileStream fStream;   if (File.Exists(_fileName))   {      range = new TextRange(RTB.Document.ContentStart, RTB.Document.ContentEnd);      fStream = new FileStream(_fileName, FileMode.OpenOrCreate);      range.Load(fStream, DataFormats.XamlPackage);      fStream.Close();   }} private void PrintCommand(){   PrintDialog pd = new PrintDialog();   if ((pd.ShowDialog() == true) )   {      //use either one of the below      pd.PrintVisual(RTB as Visual, "printing as visual");      pd.PrintDocument((((IDocumentPaginatorSource)RTB.Document).DocumentPaginator), 
"printing as paginator");   }}

Comments

  • Anonymous
    July 25, 2006
    I'm getting a weird behavior when printing with DocumentPaginator; the text is organized into 3 narrow columns on the page?

    BR

  • Anonymous
    October 13, 2006
    Hi... And if i want to perform these actions (laod/save) in RTF format?

  • Anonymous
    October 13, 2006
    Soory for my previous question :p

  • Anonymous
    October 26, 2006
    Nice & simple but how can I specify margin settings ?