In my last post I have explained how to print visual
elements using PrintVisual method of PrintDialog. In this post, I will explain how we can print flow
documents using Print Dialog class.
As I have explained earlier in my last post, PrintDialog class
provides PrintVisual and PrintDocument methods for printing. In this post I
will demonstrated how to use PrintDocument method to print Flow Document.
PrintDocument method
accepts document in form of DocumentPaginator with print description.
DocumentPaginator is a member of interface IDocumentPaginatorSource. To create document in WPF, majorly FlowDocument and FixedDocument classes are used. FlowDocument and FixedDocument both classes implements IDocumentPaginatorSource.
So while passing FlowDocument to PrintDocument method of PrintDialog class we
just need to pass DocumentPaginator of that document.
Let’s try to understand how to print FlowDocument using PrintDocument
method of PrintDialog.
XAML
<Window x:Class="WpfApplication1.PrintDocumentDemo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Print Document Demo" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.9*" />
<RowDefinition Height="0.2*"/>
</Grid.RowDefinitions>
<FlowDocumentReader Grid.Row="0">
<FlowDocument Name="flowDocument">
<Paragraph FontSize="20"
FontWeight="Bold">Printing
document</Paragraph>
<Paragraph FontSize="15">This
is sample text to be printed.</Paragraph>
</FlowDocument>
</FlowDocumentReader>
<Button Content="Print"
Height="30" Width="150"
Grid.Row="1" Click="Button_Click" />
</Grid>
</Window>
Code
private void Button_Click(object sender, RoutedEventArgs
e)
{
PrintDialog pd = new
PrintDialog();
if (pd.ShowDialog() != true)
return;
flowDocument.PageHeight = pd.PrintableAreaHeight;
flowDocument.PageWidth = pd.PrintableAreaWidth;
IDocumentPaginatorSource idocument = flowDocument as IDocumentPaginatorSource;
pd.PrintDocument(idocument.DocumentPaginator, "Printing
Flow Document...");
}
Output
As demonstrated in above code, I have written XAML code to create FlowDocument under FlowDocumentReader and added few text lines
as paragraph which I wanted to print in page when user clicks on Print button.
In code, I have created an instance of PrintDialog class and set FlowDocument height and width to match with printable area of
PageDialog. After that I have called PrintDocument method of PrintDialog class and
passed DocumentPaginator of FlowDocument with some description.
See Also –
No comments:
Post a Comment