PDFRasterizer.NET 4.0 is now available. Supports .NET Core. Renders pixel-perfectly.

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.

Download PDFRasterizer.NET 3.0
We will send you a download link

  • This field is for validation purposes and should be left unchanged.
Why do we ask your email address?
We send tips that speed up your evaluation
We let you know about bug fixes
You can always unsubscribe with one click
We never share your address with a 3rd party
Thank you for your download

We have sent an email with a download link.