Monthly Archives: February 2016

Displaying PDF files in a UWP app

In this short blogpost I want to show you how I’ve used the Windows.Data.Pdf.PdfDocument class in order to render a PDF file inside my UWP app.
In order to open a PDF from a UWP app, you can ofcourse, always use Windows.System.Launcher.LaunchUriAsync like this:
This works great, but your file is being opened in an other app. And this might not be what you want. We just want the content of the PDF file being rendered inside our UWP app itself.
PDF content in UWP

PDF content in UWP

And that’s very simple to do!
First we need to load a PDF document in a Windows.Data.Pdf.PdfDocument object. There are two way to do this: From a StorageFile or from a Stream.

This PdfDocument object has a method GetPage(int pageIndex) which returns a PdfPage object. This object represents a single page of our PdfDocument and has this interesting method: RenderToStreamAsync. This method accepts a IRandomAccessStream and optionally PdfPageRenderOptions.
Once the page is rendered to the Stream, we can set it to a BitmapImage by using the BitmapImage‘s SetSource(Asyc) method.

This BitmapImage can now be easily bound to the Source property of an Image in XAML. Or, in this case, we can bind our collection of PdfPages to an ItemsControl and display an Image for each item.

 Complete code-behind:

And that’s all there is to it!

UPDATE

I made a PdfViewerControl you can use in order to easily display PDF files in your UWP apps. It’s available, together with the source code in GitHub.
See this blogpost: UWP Simple PDF viewer