Silverlight 4: New features overview (Part 2) – Printing Support
In previous part (here) I’ve created sample application which uses Webcam and captures the image.
In this post I’ll show how to print received image (and any part of the UI) to a printer.
In Silverlight 4 we got new class, called PrintDocument which is a part of “System.Windows.Printing” namespace.
This class provides a number of events, which helps to control the printing job:
- StartPrint – occurs right after printer selection dialog successfully returns, prior the first page print
- PrintPage – occurs when page is printing. Allows to control what will be printout on the page, size of printed area and addition printable pages
- EndPrint – occurs after the printing operation complete (even if user cancel printing job)
In addition it exposes DocumentName property, in order to identify the document between printer jobs.
In my sample application I added a “Print” button, and will print 2 pages – one with the webcam image (the rectangle) and one with the buttons stack panel.
Updated application’s UI:
Now the interesting part – the “Print” button handler function:
int PageNumber = 0;
private void btnPrint_Click(object sender, RoutedEventArgs e)
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += (s, args) =>
{
if (PageNumber == 0) //If first page – print the rectangle
{
args.HasMorePages = true;
args.PageVisual = rectFill;
args.PrintableArea = new Size(rectFill.ActualWidth, rectFill.ActualHeight);
PageNumber++;
}
else //Otherwise – print the stack panel contents
{
args.HasMorePages = false;
args.PageVisual = stkButtons;
args.PrintableArea = stkButtons.RenderSize;
}
};
pd.StartPrint += (s, args) =>
{
//Prepare for first page print here...
};
pd.EndPrint += (s, args) =>
{
//Handle possilbe print errors here...
};
pd.DocumentName = "Silverlight 4 Test Document"; //This is optional, but helps to identify the print job
pd.Print(); //Start printout
}
While printing the printer queue shows the document:
This way any UIElement could be printed to any installed printer. I’ve printed the document to XPS printer driver, so resulting XPS document has to pages:
Updated sample here.
Next time I’ll show how to take this application out of browser, elevate the permissions and use COM automation.
Stay tuned,
Alex