Open a PDF from local storage in MAUI

Nutrient MAUI SDK supports opening a document from a number of sources, including local storage.

Introduction

To open a document, you need to add PDFView to your desired XAML. You’ll also need to assign a Name for interacting with it through code. In this example, PDFView is named PDFView:

<pspdfkit:PDFView x:Name="PDFView" Initialized="OnPDFViewInitialized"
                  License="{OnPlatform 
                    Android={StaticResource AndroidLicenseKey},
                    iOS={StaticResource iOSLicenseKey},
                    MacCatalyst={StaticResource MacCatalystLicenseKey},
                    WinUI={StaticResource WindowsLicenseKey}}" />

The rest of the document opening process needs to be done after the PDFView control is loaded. The easiest way to ensure it’s loaded is by using the PDFView.Initialized event as shown above. Alternatively, you can subscribe to it in code-behind as follows:

PDFView.Initialized += (sender, e) =>
{
    // ...
};

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

Opening a document from local storage

There are two ways to invoke a file picker to let the user select a document to open.

Invoked by Nutrient MAUI SDK

Information

We recommend invoking the file picker through Nutrient, as it has been optimized to load documents more quickly.

To invoke the file picker from Nutrient MAUI SDK, first open a document from the app assets folder to initialize the SDK. This can be a document like the one in our Catalog app, blank.pdf. The following example code demonstrates how to show the file picker to let the user select a document to open:

try 
{
    var document = await PSPDFKitController.LoadDocumentFromAssetsAsync(
        "blank.pdf",
        PSPDFKitController.CreateViewerConfiguration());
}
catch (Exception ex)
{
    // Handle exception.
}

Once the document is loaded in the Nutrient MAUI SDK, users can use the file picker button on the toolbar and select a document to open.

Invoked by code outside the Nutrient MAUI SDK environment

Note that there’s a platform-specific setup required for FilePicker. It’s worth reading about the setup here if you’re not familiar with it.

The following example code demonstrates how to show the file picker to let the user select a document to open:

FileResult result = null;

// Ensure that the file picker is shown on the UI thread.
await Application.Current!.Dispatcher.DispatchAsync(
    async () =>
    {
        result = await FilePicker.Default.PickAsync();
    });

if (result == null)
{
    return;
}

try
{
    var document = await PSPDFKitController.LoadDocumentAsync(result.FullPath,
        PSPDFKitController.CreateViewerConfiguration());
}
catch (Exception ex)
{
    // Handle exception.
}