Open a Local PDF File in UWP

PSPDFKit for Windows supports a number of different ways of opening documents, including using Microsoft’s StorageFile.

Note that UWP introduces very specific rules around file access permissions, and it’s worth reading about them here if you’re not familiar.

Microsoft also has several guide articles that cover topics such as working with file pickers, tracking recently used files, and much more.

Introduction

For opening a document, you must have added a PdfView to your desired XAML. You’ll also need to assign a Name for interacting with it through code. In this example, thePdfView is simply named PDFView:

<pspdfkit:PdfView License="{StaticResource PSPDFKitLicense}" Name="PDFView"/>

The rest of the process needs to be done after the PdfView Control is loaded. The easiest way to ensure that is the case is by using the PdfView.InitializationCompletedHandler event:

PDFView.InitializationCompletedHandler += (pdfView, document) =>
{
    // ...
};

If you don’t intend to open a document straight away, and you know that the PdfView will always be initialized, you can skip this step and open the document whenever it’s convenient by referring to the following sections.

Opening the Document

UWP represents files with the StorageFile class. For displaying it, you must use the relevant creator method from DocumentSource. These creators instantiate a DocumentSource, which is then used by the PdfView like so:

// Open and display the PDF in the PSPDFKit `PdfView`.
var documentSource = DocumentSource.CreateFromStorageFile(file);
await PDFView.Controller.ShowDocumentAsync(documentSource);

A StorageFile must be located and retrieved before being displayed. This can be done, for example, by using a file picker to present a Windows-native UI to the user.

The following example code demonstrates how to show the file picker to let the user selected a StorageFile:

// Open a picker so the user can choose a PDF.
var picker = new FileOpenPicker
{
    ViewMode = PickerViewMode.Thumbnail,
    SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
    FileTypeFilter = { ".pdf" }
};

var file = await picker.PickSingleFileAsync();
if (file == null) return;

We use cookies to improve your experience and for marketing. Learn more in our privacy policy.