When you work with WPF, you can easily print visual content in to image by using RenderTargetBitmap and call render with WPF visual content.
But there are some problems when you want to print the content which currently not showed on screen. For example if you want to print all Tab pages, you will have a problem because your content has to be showed on the screen before using Render method.
In this blog post it will be implement demo sample how to print all tab pages in to PNG image format.
The idea behind this implementation was that during switching between tabpage, create background thread wait some millisecond, back to UI thread and Render visuals in to image, then proceed to next tab page with same steps.
All said can be described in the following source code sample.
//Print all tab pages private void button1_Click(object sender, RoutedEventArgs e) { //select firts page tabCtrl.SelectedIndex = 0; //create background thread and wait some time new Thread(new ThreadStart(() => { Thread.Sleep(500); //back to UI thread and print visual content this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => { var st1 = CreateImage(((TabItem)tabCtrl.Items[0]).Content as FrameworkElement); saveImage(st1, "c:/temp/page1.png"); //select next tab page tabCtrl.SelectedIndex = 1; //create background thread new Thread(new ThreadStart(() => { //wait some time Thread.Sleep(500); //back to UI thread and render visuals to bitmap this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => { var st2 = CreateImage(((TabItem)tabCtrl.Items[1]).Content as FrameworkElement); saveImage(st2, "c:/temp/page2.png"); //select thrid page and wait some time tabCtrl.SelectedIndex = 2; new Thread(new ThreadStart(() => { Thread.Sleep(500); //back to UI thread and print to bitmap this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new Action(() => { var st3 = CreateScaledImage(((TabItem)tabCtrl.Items[2]).Content as FrameworkElement, 120,120); saveImage(st3, "c:/temp/page3.png"); })); })).Start(); })); })).Start(); })); } )).Start(); }
In the previous method we have created three background thread waited some time to alow main thread to render content, back to UI thread and render visual elements. The result of caling prevous method is the following image files on C:/Temp directory.
The whole demo sample with source code can be found here.
Pingback: Using RenderTargetBitmap to print non selected tab pages - C# & .NET technologies - developers.de
Thank you for your example. I have actually the problem to print out two tabs in one document one two pages and had hoped that you can help me. But first the link to the source seems to be broken and second I have problems in converting the stuff to vb.net. Maybe you can help me out here…
I have checked the link, and seems it is OK.
For the second question try to use Telerik Converter it is very powerful: http://converter.telerik.com/