Wednesday 4 September 2013

Printing Flow Document using WPF PrintDialog

     Printing Flow Document using WPF PrintDialog



PrintDocument method accepts document in form of DocumentPaginator with print description. DocumentPaginator is a member of interfaceIDocumentPaginatorSource. To create document in WPF, majorly FlowDocument and FixedDocument classes are used. FlowDocument andFixedDocument 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() != truereturn;

    flowDocument.PageHeight = pd.PrintableAreaHeight;
    flowDocument.PageWidth = pd.PrintableAreaWidth;

    IDocumentPaginatorSource idocument = flowDocument asIDocumentPaginatorSource;

    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.

No comments:

Post a Comment