Open PDF files in Flutter

Nutrient Flutter SDK allows you to open documents using PspdfkitWidget or the Pspdfkit.present() method. This article serves as a step-by-step guide to get you started quickly.

Opening a PDF

If you’re trying to open a PDF file that has been stored as an asset, you first need to copy that file to a temporary directory. Once that’s done, you can open it.

Here’s a helper function to copy the file to a temporary directory:

Future<File> extractAsset(String assetPath) async {

    // On Web, we can directly use the asset path.
    if(kIsWeb) return File(assetPath);

    final bytes = await DefaultAssetBundle.of(context).load(assetPath);
    final list = bytes.buffer.asUint8List();

    final tempDir = await Pspdfkit.getTemporaryDirectory();
    final tempDocumentPath = '${tempDir.path}/$assetPath';

    final file = await File(tempDocumentPath).create(recursive: true);
    file.writeAsBytesSync(list);
    return file;
}

Here’s how you can open a PDF document using PspdfkitWidget:

final extractedDocument = await extractAsset(_documentPath);

...

Scaffold(
    extendBodyBehindAppBar: true,
    appBar: AppBar(),
    body:PspdfkitWidget(
        documentPath: extractedDocument.path)
    );
...

And here’s how you can open a PDF document using the global present() method:

final document = await extractAsset(documentPath);
wait Pspdfkit.present(document.path);

The present() method is a global method that can be called from anywhere in your app. It’s only supported on iOS and Android.

For more details about how to open a document using Nutrient Flutter SDK, see our getting started guides or try our Catalog example project.

Opening an image

In addition to PDF documents, Nutrient Flutter SDK also allows you to open and annotate images (PNG and JPEG). The following example shows how to open a PNG image using the present() method:

final extractedImage = await extractAsset(imagePath);
await Pspdfkit.present(extractedImage.path);

Document loaded callback

Starting with Nutrient Flutter SDK version 3.10, you can use the onDocumentLoaded callback to get notified when a document has been loaded. This is called with the PdfDocument object as an argument:

PspdfkitWidget(
    documentPath: extractedDocument.path,
    onDocumentLoaded: (PdfDocument pdfDocument) {
        print('Document loaded: ${pdfDocument.documentId}');
    },
);