Silverlight 4 Printing API

One of the new features of Silverlight 4 is the printing API. This is really a huge thing because printing in previous version was really pain to do. So I decided to play around with the API to see what the possibilities are.

In my example I created a “Hello World” application that contains a textblock and a button. By pressing the button the system will print the screen.

XAML:

<Grid x:Name=”LayoutRoot” Background=”White”>

<Grid.RowDefinitions>

<RowDefinition Height=”auto” />

<RowDefinition Height=”auto” />

</Grid.RowDefinitions>

<StackPanel Margin=”10 ” Orientation=”Horizontal” Grid.Row=”0″ >

<TextBlock Name=”txtTextToPrint” Margin=”5″ Text=”Hello World! I am printing from Silverlight.”></TextBlock>

<Button Click=”Button_Click” Content=”Print”></Button>

</StackPanel>

</Grid>

Code behind:

private void Button_Click(object sender, RoutedEventArgs e)

{

PrintDocument pd = new PrintDocument();

pd.DocumentName = “SilverlightPrintTest”;

pd.PrintPage += new EventHandler<PrintPageEventArgs>(pd_PrintPage);

pd.Print();

}

void pd_PrintPage(object sender, PrintPageEventArgs e)

{

e.PageVisual = LayoutRoot;

}

Print output :

This code lets me print the whole screen that you see because I set the PageVisual = LayoutRoot. The PageVisual property excepts a UIElement so if you only want to print a specific control then you do e.PageVisual = nameOfYourControl. In fact in my sample the LayoutRoot is the root UEIlement of the page.

In my sample  I use the new PrintDocument class. This class is located in the System.Windows.Printing namespace.  The most important things on this class are the following 3 events:

  • PrintPage: occurs each time a page is printing.
  • StartPrint: occurs before the PrintPage event.
  • EndPrint: occurs after the PrintPage event. Is mostly used to handle any errors that occurred during printing.

Mike Taulty has a more in depth sample in this blog post: http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/11/18/silverlight-4-rough-notes-printing.aspx

~ by kittysn1per on November 22, 2009.

Leave a Reply