Pages

Saturday, February 4, 2012

WPF Printing

Printing in the WPF can be achieved by the method Print in the PrintDialog class.

Methods in PrintDialog class.

1. PrintVisual.
2. PrintDocument.

Both are having different use cases like Single Page and Mulitple pages.

Single Page :-

Actually PrintVisual method is responsible to print the single page visual. Calling PrintVisual will always print what you give it in a single page and it will be placed in the very upper left page. This means that if your visual is larger than a page, it will get clipped, and if your visual has no built in margin, it will probably clip a little bit on the edges.

XAML


<Grid ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid>
            <Button Content="Press me to Print...." Margin="5" x:Name="print" HorizontalAlignment="Center" Click="print_Click" />
        </Grid>
        <Grid Grid.Row="1"  Margin="5" x:Name="printme">
            <StackPanel Orientation="Vertical">
                <TextBlock Text="I will be printed if you press the above the Print button"/>
                <Image Source="Best_Practices_226.jpg" Height="300" Width="400"/>
            </StackPanel>            
        </Grid>
    </Grid>


In the above code. I am just going to print the printme grid. Respective C# code is below.

C#


public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
 
        private void print_Click(object sender, RoutedEventArgs e)
        {
            PrintDialog printdialog = new PrintDialog();
            if ((bool)printdialog.ShowDialog())
            {
                printdialog.PrintVisual(printme, "Print");
            }
        }
    }


Now it will just print the printme grid with the content inside it.