Open PDF Files in Flutter

PSPDFKit for Flutter 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 PSPDFKit for Flutter, see our getting started guides or try our Catalog example project.

Opening an Image

In addition to PDF documents, PSPDFKit for Flutter 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);