Skip to content

Open a Document

ComPDFKit PDF SDK for Flutter allows you to open documents using CPDFReaderWidget or the ComPDFKit.openDocument() method. This article serves as a step-by-step guide to get you started quickly.

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:

dart
Future<File> extractAsset(BuildContext context, String assetPath,
    {bool shouldOverwrite = true, String prefix = ''}) async {
  final bytes = await DefaultAssetBundle.of(context).load(assetPath);
  final list = bytes.buffer.asUint8List();

  final tempDir = await ComPDFKit.getTemporaryDirectory();
  final tempDocumentPath = '${tempDir.path}/$prefix$assetPath';
  final file = File(tempDocumentPath);

  if (shouldOverwrite || !file.existsSync()) {
    await file.create(recursive: true);
    file.writeAsBytesSync(list);
  }
  return file;
}

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

dart
File document = await extractAsset(context, _documentPath, shouldOverwrite: false);
...
Scaffold(
  resizeToAvoidBottomInset: false,
  appBar: AppBar(),
  body: CPDFReaderWidget(
    document: document.path,
    configuration: CPDFConfiguration(),
    onCreated: (controller) {

    },))
...

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

dart
File document = await extractAsset(context, _documentPath);

ComPDFKit.openDocument(document.path, password: '', configuration: CPDFConfiguration());