Rendering a PDF page may take long (>100 ms). In order to keep the UI responsive, it should not be performed on the UI thread.

Rendering a PDF page may take long (>100 ms). In order to keep the UI responsive, it should not be performed on the UI thread.


At first glance WPF seems to have a nice solution for this: The BackgroundWorker is the recommended way to run time-consuming tasks on a separate, dedicated thread, leaving the UI responsive. A background worker is created as follows:

BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += new DoWorkEventHandler(doWork); worker.RunWorkerAsync();

Event handler doWork would do the actual rendering to WPF graphics. It turns out that it is not possible to create even a simple rectangle from the worker thread, let alone all possible elements of a PDF page. If we use the following doWork event handler:

void doWork(object sender, DoWorkEventArgs e) { Rectangle rectangle = new Rectangle();

An InvalidOperationException is thrown: "The calling thread must be STA, because many UI components require this." It is not possible to change the background worker thread to STA. It uses a threadpool thread and these are always MTA and cannot be changed.

STA Thread

So let's create our own background thread and set the apartment state to STA and render the PDF pages to WPF graphical element from this.

Thread thread = new Thread(new ThreadStart(doWork)); thread.SetApartmentState(ApartmentState.STA); thread.Start();

private void doWork() { Rectangle rectangle = new Rectangle();

This code runs nicely. But now we need to display our rectangle in the UI.


We need to pass the result to the UI thread. This is what the dispatcher is designed to do. Each thread in a WPF application has a dispatcher which queues a piece of code along with some data to the user interface thread. The user interface thread will schedule and run the code, which uses the data to update the screen.

private void doWork() { Rectangle rectangle = new Rectangle();

this.Dispatcher.Invoke( (Action) delegate () { drawResult(rectangle); }); }

private void drawResult(Rectangle rectangle) { canvas1.Children.Add(rectangle); }

Now we get the exception "The calling thread cannot access this object because a different thread owns it". What you see here is a protection against a typical multi-threading problem: one thread can change data at the same time that another thread is reading it, which may give unpredictable results.

The usual locking using semaphores could be useful here but apparently this is not the WPF way of working. Instead a "freeze" must be performed to make objects unchangeable. The user interface thread will know then that a graphical element is not going to change anymore and can draw it safely on the screen. Unfortunately, not all graphical objects are freezable. E.g. a Brush is, but a Rectangle isn't.

Take an XPS or XAML detour

We could take a detour: the background thread creates visual elements and converts these to XPS which the user interface thread can read. It would have been convenient to be able to write XPS to a memory stream but this is not possible; Microsoft insists that XPS is written to a file first.

A bit less awkward is to use XAML instead of XPS which can use memory stream. Here is the code:

public void StartTextAndRectangleDrawingThread() { var t = new Thread (new ThreadStart(this.TextAndRectanglesCreatingThread)) { IsBackground = true }; t.SetApartmentState(ApartmentState.STA); t.Start(); }

private void TextAndRectanglesCreatingThread() { var canvas = new Canvas{ Width = 300, Height = 300 }; var text = new TextBlock { Text = "Hello", FontSize = 32 }; canvas.Children.Add(text); Canvas.SetLeft(text, 100); Canvas.SetTop(text, 100); var brush = new SolidColorBrush(Color.FromRgb(200, 20, 50)); var rectangle = new System.Windows.Shapes.Rectangle { Width = 40, Height = 50, Fill = brush, }; canvas.Children.Add(rectangle); Canvas.SetLeft(rectangle, 50); Canvas.SetTop(rectangle, 50);

var stream = new MemoryStream(); System.Windows.Markup.XamlWriter.Save(canvas, stream); Application.Current.Dispatcher.BeginInvoke( DispatcherPriority.Normal, (Action<MemoryStream>) this.TextAndRectangleDrawingThreadHasData, stream);}

void TextAndRectangleDrawingThreadHasData(MemoryStream stream) { stream.Seek(0, SeekOrigin.Begin); var textAndRextangle = (Canvas)System.Windows.Markup.XamlReader.Load(stream); this.PdfLayer.Children.Add(textAndRextangle); }

For code that draws some text and rectangles it works fine, however, converting a PDF first to WPF and then to XAML gives many problems which may be solvable, but ends up in a long and inefficient chain of conversions. Especially in the context of PDF documents with large amounts of complex content this is not the way to go.

Solution: Render to a bitmap in the background

The best solution that we found was to move as much as possible to the background thread, including the rendering to a bitmap for display on screen. We use RenderTargetBitmap for this purpose (which is "freezable").

The order of events is now:

1. The user interface thread starts a background thread with a file name and the dimensions of the bitmap.

2. This background thread opens a PDF document and:

  • parses its content
  • performs TALLcomponents -> ConvertToWpf
  • creates a transformation matrix for scaling the PDF page into the bitmap,
  • render it into a bitmap using WPF -> RenderTargetBitmap -> Render,
  • Freeze the bitmap.

3. The background thread dispatches a piece of code and the frozen bitmap to the user interface thread.

4. This code is scheduled in the user interface thread and it draws the bitmap on a canvas.

A simple sample app is made that renders a PDF document while user interface handles the drawing on a ink canvas, which works smoothly whatever the size and complexity of the PDF document.

The code for the background thread is:

// Create bitmap private void OpenPdf() { var openFileDialog = new Microsoft.Win32.OpenFileDialog { DefaultExt = ".pdf", Filter = "PDF files (*.pdf)|*.pdf|All files (*.*)|*.*" }; bool? fileOpenResult = openFileDialog.ShowDialog(); if (fileOpenResult == true) { _threadThatRendersThePdf = new Thread(() => RenderPdfDocument( pdfFileName: openFileDialog.FileName, imageWidth: this.CanvasWidth, imageHeight: this.CanvasHeight)); _threadThatRendersThePdf.SetApartmentState(ApartmentState.STA); _threadThatRendersThePdf.Start(); } }

void RenderPdfDocument(string pdfFileName, double imageWidth, double imageHeight) { const double WpfDpi = 96.00; // WPF measures in 96 DPI const double PdfDpi = 72.00; // PDF measures in 72 DPI using (var pdfStream = new FileStream(pdfFileName, FileMode.Open, FileAccess.Read)) { var pdfDocument = new TallComponents.PDF.Rasterizer.Document(pdfStream); var pdfPage = pdfDocument.Pages[0];

// Get the scale to let it fit into the image size,
// WPF measures things in 96th of an inch, not in pixels
// PDF width and height are measured in points
double scaleX = (imageWidth / WpfDpi) / (pdfPage.Width / PdfDpi);
double scaleY = (imageHeight / WpfDpi) / (pdfPage.Height / PdfDpi);
double scale = Math.Min(scaleX, scaleY);

// Resize the bitmap area so that is has the same width/height ratio 
// as the PDF page, this possibly makes either the width or the height
// of the bitmap smaller. 
// The rendered PDF will fit exactly in the image this way.
double ratioPdf = pdfPage.Height / pdfPage.Width;
double ratioImage = imageHeight / imageWidth;
double bitmapWidth = ratioPdf &gt; ratioImage 
                   ? imageHeight / ratioPdf 
                   : imageWidth;
double bitmapHeight = ratioPdf &gt; ratioImage 
                   ? imageHeight 
                   : imageHeight * ratioPdf;

// render the page to WPF into the resized image
var renderSettings = new RenderSettings();
var convertToWpfOptions = new ConvertToWpfOptions();
var summary = new TallComponents.PDF.Rasterizer.Diagnostics.Summary();
convertToWpfOptions.ConvertToImages = false;
var wpfPage = pdfPage.ConvertToWpf(renderSettings,

// make a bitmap renderer for the WPF page (but dont render it yet)
// and wrap a container around the wpfPage to that we can scale it 
// to dimensions of the bitmap then let WPF render it and finally 
// freeze it so it can be passed to the UI thread.
var wpfPageAsBitmap = 
               new System.Windows.Media.Imaging.RenderTargetBitmap(
                   pixelWidth: (int)bitmapWidth,
                   pixelHeight: (int)bitmapHeight,
                   dpiX: WpfDpi,
                   dpiY: WpfDpi,
             pixelFormat: System.Windows.Media.PixelFormats.Default);
var container = new System.Windows.Media.ContainerVisual
     { Transform = new ScaleTransform(scale, scale) };

// Transport the frozen bitmap of the page to the UI Tread 
BitmapThreadDelegate delegateToDrawInUiThread = BitmapUIThreadTask;

} }

public void BitmapUIThreadTask( System.Windows.Media.Imaging.RenderTargetBitmap bitmap) { var image = new Image() { Source = bitmap, Stretch = Stretch.None }; this.PdfLayer.Children.Add(image); }

private delegate void BitmapThreadDelegate( System.Windows.Media.Imaging.RenderTargetBitmap bitmap);

private Thread _threadThatRendersThePdf;

The canvas that contains the PDF may be placed below a a ink panel so that a user can draw on top of a PDF page:

<inkcanvas height="350" horizontalalignment="Left" margin="10,10,0,0" name="ViewboxInkAndPDF" strokes="{Binding Path=InkStrokes}" verticalalignment="Top" width="300"> <canvas> <contentpresenter content="{Binding PdfLayer}"> </contentpresenter></canvas> </inkcanvas>