Open PDFs from a Custom Data Provider in UWP

In addition to loading documents directly using StorageFile, IBuffer, or a Uri, PSPDFKit for Windows includes support for creating DocumentSources from data providers. A data provider defines a common interface for PSPDFKit to read and write PDF documents from custom sources. This is especially helpful if you want to support your own encryption or compression scheme.

Existing Data Providers

PSPDFKit for Windows ships with two predefined providers:

You can also write your own custom data providers by implementing the IDataProvider interface. The Catalog project contains another two examples of custom providers:

These providers can be used to create a DocumentSource, which is then used by the Controller to display the document:

_fileStream = await file.OpenAsync(FileAccessMode.ReadWrite);

var dataProvider = new ExampleDataProvider(_fileStream);
var documentSource = DocumentSource.CreateFromDataProvider(dataProvider);

await PDFView.Controller.ShowDocumentAsync(documentSource);

Custom Data Provider

To create your own custom data provider, you’ll have to create a class that implements the IDataProvider interface and all its methods. These methods should help you structure your data in a way that’s compatible with PSPDFKit for Windows.

Reading

For reading, the ReadAsync method is used internally when needed. The content of this method will vary depending on how documents are obtained in your own application. Within the ReadAsync method, your chosen data structures should be adapted to match the IBuffer return expected by PSPDFKit for Windows, like so:

private readonly IRandomAccessStream _data;

private async Task<IBuffer> ReadAsync(uint size, uint offset)
{
    if (offset >= _data.Size)
    {
        throw new Exception("Attempt to read beyond the end of a random access stream.");
    }

    var copy = new Buffer(size);
    _data.Seek(offset);
    return await _data.ReadAsync(copy, size, InputStreamOptions.ReadAhead);
}

Note that your method must ensure the size and offset used for the reading operation are valid according to your data.

For extra examples, please check our Catalog application, which includes two sample IDataSink implementations. For writing to a data sink, please see our Save a Document to a Custom Data Provider guide.