On www.silverlight.net several people are asking how to print the values of a DataGrid in Silverlight. You cannot just assign the DataGrid to the PageVisual-Property of the PrintPageEventArgs. This would just print the DataGrid as it is on one page. The data wouldn’t be splitted on several pages, cause there’s no paging logic to use. You’ve to write this logic.
You’re responsible for the paging! But how to do it? In this post I’ll give you a little idea how it could work by simple printing out a List of string-values. I won’t talk a lot about the details. Just look at the code below:
public partial class MainPage : UserControl { private List<string> _list; private const double ROWHEIGHT = 20; private const double PAGEMARGIN = 30; public MainPage() { InitializeComponent(); _list = new List<string>(); for (int i = 1; i < 101; i++) { _list.Add(i + " thanks to Thomas for this printing sample"); _list.Add("Visit http://www.thomasclaudiushuber.com"); } } private void Button_Click(object sender, RoutedEventArgs e) { _currentIndex = 0; var pd = new PrintDocument(); pd.DocumentName = "AListFromThomas"; pd.PrintPage += pd_PrintPage; pd.Print(); } private int _currentIndex; private double _currentTop; private double _availableSpace; void pd_PrintPage(object sender, PrintPageEventArgs e) { var pageRoot = new Canvas(); e.PageVisual = pageRoot; _currentTop = PAGEMARGIN; _availableSpace = e.PrintableArea.Height - PAGEMARGIN*2; while (_currentIndex < _list.Count) { var txt = new TextBlock { Text = _list[_currentIndex] }; if (ROWHEIGHT > _availableSpace) { e.HasMorePages = true; break; } txt.SetValue(Canvas.TopProperty, _currentTop); txt.SetValue(Canvas.LeftProperty, PAGEMARGIN); pageRoot.Children.Add(txt); _currentTop += ROWHEIGHT; _availableSpace -= ROWHEIGHT; _currentIndex++; } } }
When the Button_Click-Eventhandler is executed, the List gets printed over 5 pages. You can easily print it to PDFCreator or XPS Printer to test it. The output looks like this:
Download the source here and enjoy. Give me feedback by entering a comment to this blogentry or via email on www.thomasclaudiushuber.com/blog.