Welcome to MSDN Blogs Sign in | Join | Help

Lester's WPF blog


Simple, easy & beautiful

News

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

   }

}

Posted: Tuesday, May 16, 2006 11:15 PM by llester
Filed under: , , ,

Comments

ThomasAndersendk said:

I'm getting a weird behavior when printing with DocumentPaginator; the text is organized into 3 narrow columns on the page?

BR

# July 26, 2006 5:41 AM

Alex said:

Hi...

And if i want to perform these actions (laod/save) in RTF format?

# October 13, 2006 8:08 AM

Alex said:

Soory for my previous question :p

# October 13, 2006 8:12 AM

Jan Willem said:

Nice & simple but how can I specify margin settings ?

# October 26, 2006 3:48 PM
New Comments to this post are disabled
Page view tracker