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

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

This code sample helps 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

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:

...
var container = new System.Windows.Media.ContainerVisual 
    { 
        Transform = new ScaleTransform(scale, scale) 
    };

container.Children.Add(wpfPage);
wpfPageAsBitmap.Render(container);
wpfPageAsBitmap.Freeze();

// Transport the frozen bitmap of the page to the UI Tread 
BitmapThreadDelegate delegateToDrawInUiThread = this.BitmapUIThreadTask;
                  Application.Current.Dispatcher.BeginInvoke(
                  DispatcherPriority.Background,
                  delegateToDrawInUiThread,
                  wpfPageAsBitmap,
                  pageNr,
                  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:

var canvas = new Canvas { Width = this.CanvasWidth, Height = this.CanvasHeight };
...
var stream = new MemoryStream();
System.Windows.Markup.XamlWriter.Save(canvas, stream);
Application.Current.Dispatcher.BeginInvoke(
            DispatcherPriority.Normal,
            (Action<MemoryStream>)this.TextAndRectangleDrawingThreadHasData,
            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

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