Display PDF in a WPF app and stay responsive - the code

WPF / XPS
4/11/2014

Downloads

I couple of months ago I wrote a blog on how to stay responsive while rendering a a PDF document in a WPF application. On readers request the complete project is available for download now.

Threading in WPF

In a blog I wrote about rendering a PDF document in a background, while the user interface stayed repsonsive, see this blog.

The difficult part was to find a way around the "The calling thread must be STA, because many UI components require this." and how to "freeze" the generated image so it can be passed to the user interface thread. This code accomplishes exactly that:

1 ... 2 var container = new System.Windows.Media.ContainerVisual 3 { 4 Transform = new ScaleTransform(scale, scale) 5 }; 6 7 container.Children.Add(wpfPage); 8 wpfPageAsBitmap.Render(container); 9 wpfPageAsBitmap.Freeze(); 10 11 // Transport the frozen bitmap of the page to the UI Tread 12 BitmapThreadDelegate delegateToDrawInUiThread = this.BitmapUIThreadTask; 13 Application.Current.Dispatcher.BeginInvoke( 14 DispatcherPriority.Background, 15 delegateToDrawInUiThread, 16 wpfPageAsBitmap, 17 pageNr, 18 progress);

The code sample also demonstrates the more usual way to do this with a thread that writes some text and graphics, using the XAML detour like this:

1 var canvas = new Canvas { Width = this.CanvasWidth, Height = this.CanvasHeight }; 2 ... 3 var stream = new MemoryStream(); 4 System.Windows.Markup.XamlWriter.Save(canvas, stream); 5 Application.Current.Dispatcher.BeginInvoke( 6 DispatcherPriority.Normal, 7 (Action<MemoryStream>)this.TextAndRectangleDrawingThreadHasData, 8 stream);

Note that this code should not be used for complex PDF pages, as it is not very efficient and you may get an "A fixedPage cannot contain another fixedPage" exception.

An example WPF application

WpfBackgroundThread.PNG

This application demonstrates a responsive ink panel, PDF rendering in the background and a demonstration thread for text and simple images.

Download

All the code you need to reproduce this in now available, see the link on top of this page.