This is the first part of a series of posts about printing in WPF starting from printing a single element and going all the way to advanced topics like background printing and XPS.
We will start this series with absolutely the simplest WPF application that prints something, we will create a window with a single button – and we will then print this button.
The gateway into the WPF printing system is the System.Windows.Controls.PrintDialog class, this class manages printer settings and let you do the actual printing, it is also, as the name suggests, the print dialog – but you don’t have to show the print dialog in order to use it to print.
PrintDialog has two methods you can use to print stuff, PrintVisual and PrintDocument, PrintVisual is the easier of the two so we’ll start with it – it’s also mostly useless in real world scenarios so we probably wouldn’t talk about it again in this series.
Let’s start, create a new WPF application and add this inside Window1.xaml:
<Button Name=”PrintButton” Content="Print Me!" Click="Print_Click"/>
And this in the Window1.xaml.cs file:
private void Print_Click(object sender, RoutedEventArgs e)
{
PrintDialog dlg = new PrintDialog();
dlg.PrintVisual(PrintButton, "Print Button");
}
Those two lines of code will print an image of the button to the default printer, the “Print Button” string is the document name you can see it if you open the printer queue window (Start -> Control Panel -> Printers and Faxes -> printer name).
Here is a slightly longer version that will let the user choose a printer:
private void Print_Click(object sender, RoutedEventArgs e)
{
PrintDialog dlg = new PrintDialog();
if (dlg.ShowDialog() == true)
{
dlg.PrintVisual(Print, "Print Button");
}
}
In the next post of this series we will talk about how to choose a printer and change printer settings programmatically.
posted @ Thursday, March 19, 2009 10:45 AM