The following code snippet shows how to print a text file in RichTextBox (RTB). Using the same approach, you may use any file.
The XAML user interface is listed here:
<Window x:Class="RichTextBoxSample.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="490">
<Grid>
<RichTextBox Name="RTB" Height="167" Margin="0,0,190,95" Width="278">
<FlowDocument>
<Paragraph>
<Run>First paragraph goes here. Type some text here.</Run>
</Paragraph>
<Paragraph>
<Run>Second paragraph goes here. Type some text here.</Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
<Button Height="36" Margin="12,0,0,34" Name="button1" VerticalAlignment="Bottom"
HorizontalAlignment="Left" Width="97" Click="button1_Click">Get Contents</Button>
<Button Height="32" HorizontalAlignment="Right" Margin="0,18,15,0" Name="LoadButton"
VerticalAlignment="Top" Width="145" Click="LoadButton_Click">Load</Button>
<Button Height="37" HorizontalAlignment="Right" Margin="0,59,15,0" Name="SaveButton"
VerticalAlignment="Top" Width="144" Click="SaveButton_Click">Save</Button>
<Button HorizontalAlignment="Right" Margin="0,110,13,115" Name="PrintButton"
Width="148" Click="PrintButton_Click">Print</Button>
<Button Height="41" Margin="130,0,215,29" Name="ClearButton" VerticalAlignment="Bottom" Click="ClearButton_Click">Clear</Button>
</Grid>
</Window>
Here is the Print button click event handler.
private void PrintButton_Click(object sender, RoutedEventArgs e)
{
PrintDialog pd = new PrintDialog();
if ((pd.ShowDialog() == true))
{
//use either one of the below
pd.PrintVisual(RTB as Visual, "Print Visual");
pd.PrintDocument((((IDocumentPaginatorSource)RTB.Document).DocumentPaginator),
"Print Document");
}
}