Bagikan melalui


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");   }}