Introduction to the Silverlight Print Option

This article looks at how to implement the print option in a Silverlight application. This print feature is bundled along with the 4.0 version of Silverlight SDK. Sample source codes are provided in the following sections.

What's the Advantage of Silverlight's Print Functionality?

In most of the web based technologies there is no core support available for the print functionality. For example, if you consider an asp.net application there is no straight way to implement a print functionality. Even if there is one available like that of a Javascript print, the developer does not have good control over it. Now Silverlight 4.0 has come up with a built-in print functionality, which leverages for the developer to perform the below print tasks.

1.Print the whole Silverlight page content.

2.Print only a part of the Silverlight content.

3.Printing multiple pages including pagination.

Print Functionality Implementation

The printing in Silverlight can be achieved through the PrintDocument class, which is ingrained in the namespace System.Windows.Printing. PrintPage event should be hooked up to the PrintPageEventHandler where the Silverlight content to be printed is set. Below is the basic implementation of the print functionality.

XAML code:

<UserControl x:Class="PrintingFeatureDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="409" d:DesignWidth="768">
 
    <Grid x:Name="LayoutRoot" Background="White">
        <Canvas>
            <TextBlock Name="PrintTextBlock" Text="Text to be printed" FontSize="20" Margin="239,12,337,366"></TextBlock>
            <Image Name="PrintImage" Source="Chrysanthemum.jpg" Width="100" Height="100" Margin="286,59,382,250"></Image>
            <Button Content="Print All" Height="23" HorizontalAlignment="Left" Margin="302,181,0,0" Name="PrintAllButton" VerticalAlignment="Top" Width="75" Click="PrintAllButton_Click" />
        </Canvas>
    </Grid>
</UserControl>

The above XAML code contains a TextBlock and an Image, which should get printed by clicking on the Print button.

C# code:

namespace PrintingFeatureDemo
{
    public partial class MainPage : UserControl
    {
        PrintDocument _printAll;
 
        public MainPage()
        {
            InitializeComponent();
 
            _printAll = new PrintDocument();
            //Hooks up the PrintPageevent
            _printAll.PrintPage += new EventHandler7lt;PrintPageEventArgs>(_printDocument_PrintPage);
        }
 
        void _printDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            //Sets the Silverlight section to be printed 
            e.PageVisual = this;
        }
 
        private void PrintAllButton_Click(object sender, RoutedEventArgs e)
        {
            _printAll.Print("Silverlight Content To Be Printed");            
        }
    }
}

In the above code, notice that the PrintPage event of the PrintDocument object is used to set the PageVisual, which is nothing but the Silverlight content to be printed. The Print method pops up the print dialog box, which in turn kicks off the printing process.

The above code would print the entire Silverlight content. If you need to print only a fragment of the Silverlight content then set the PageVisual property appropriately. For example, say on clicking on print you would like to print only the image, then set the PageVisual as shown in the below code.

void _printDocument_PrintPage(object sender, PrintPageEventArgs e)
{
            //Sets the Silverlight section to be printed 
            //This sets only the image as the content to be printed
            e.PageVisual = this.PrintImage;
}

Notable Properties and Events

In this section let us explore the important events and properties which seem to be pretty useful.

BeginPrint and EndPrint Events

These events helps the developer in handling the pre and post print events like setting up and tearing up the print environment. Below is the sample implementation.

_printDocument.BeginPrint += new EventHandler(_printAll_BeginPrint);
_printDocument.EndPrint += new EventHandler(_printAll_EndPrint);
//Invoked when the print operation completes
void _printAll_EndPrint(object sender, EndPrintEventArgs e)
{
            //Check for the printing error
            if (e.Error != null)
                MessageBox.Show(e.Error.Message);//Display the error message
            else
                MessageBox.Show("Printing successful");
}
 
//Kicked off when the Print button on the print dialog is clicked
void _printAll_BeginPrint(object sender, BeginPrintEventArgs e)
{
            //Setting up operations, if at all anything required
}

HasMorePages Property

This is a property of the PrintPageEventArgs class. Set this to true incase multiple pages need to be printed until you reach the final page where this property should be set to false. This property is the key while implementing multiple page print functionality.

Fig 1.0 is a sample screenshot of the print dialog.

The SharePoint print dialog
Figure 1: The SharePoint print dialog

Conclusion

I hope this article brings out the information about implementing the print functionality in a Silverlight application. Please make use of the comments section in order to provide your thoughts.

Thanks for reading the article.



About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Download the Information Governance Survey Benchmark Report to gain insights that can help you further establish business value in your Records and Information Management (RIM) program and across your entire organization. Discover how your peers in the industry are dealing with this evolving information lifecycle management environment and uncover key insights such as: 87% of organizations surveyed have a RIM program in place 8% measure compliance 64% cannot get employees to "let go" of information for …

  • Live Event Date: April 22, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Database professionals — whether developers or DBAs — can often save valuable time by learning to get the most from their new or existing productivity tools. Whether you're responsible for managing database projects, performing database health checks and reporting, analyzing code, or measuring software engineering metrics, it's likely you're not taking advantage of some of the lesser-known features of Toad from Dell. Attend this live …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds