Skip to content
Guides

Open a Document

ComPDFKit PDF SDK for Flutter offers multiple ways to open PDF documents depending on your use case:

  • Use CPDFReaderWidget to display an embedded reader UI.
  • Use ComPDFKit.openDocument() to quickly launch a full-screen document viewer.
  • Use CPDFDocument for background processing or non-UI operations.

If your PDF is stored in the assets directory, you need to copy it to a temporary directory before opening it. Here’s a utility method for extracting asset files:

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;
}

Using CPDFReaderWidget (Recommended for embedded reader scenarios)

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

    },))
...

Using ComPDFKit.openDocument() (Quick full-screen viewer)

This is ideal for quickly launching a standalone document viewer.

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

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

Using CPDFDocument (For background or logic-only use cases)

This is useful for non-UI operations such as annotation management, import/export, etc.

dart
File document = await extractAsset(context, _documentPath);
// Create and open the document
CPDFDocument document = await CPDFDocument.createInstance();
CPDFDocumentError error = await document.open(document.path);

if (error == CPDFDocumentError.success) {
  // Perform operations with the CPDFDocument instance...
}