Skip to content
Guides

Access Annotations

To retrieve all annotations from a PDF document, follow the steps below:

Basic Steps:

  1. Obtain a document object (either from a CPDFReaderWidget controller or a CPDFDocument instance).
  2. Get the total number of pages to iterate through each one.
  3. Retrieve each page object (CPDFPage).
  4. Retrieve the list of annotations from each page.
  5. Iterate through and collect all annotations across all pages.

Using CPDFReaderWidget to Access Annotations

This is suitable for scenarios where you’re integrating with Flutter’s UI component. First, obtain a CPDFReaderWidgetController via the onCreated callback, then access the document object to read pages and annotations.

dart
CPDFReaderWidgetController? _controller;

// Initialize CPDFReaderWidget and get the controller in the onCreated callback
CPDFReaderWidget(
  document: widget.documentPath,
  password: widget.password,
  configuration: widget.configuration,
  onCreated: (controller) {
    setState(() {
      _controller = controller;
    });
  },
);

// Retrieve the annotation list
List<CPDFAnnotation> annotations = [];

if (_controller != null) {
  int pageCount = await _controller!.document.getPageCount();

  for (int i = 0; i < pageCount; i++) {
    CPDFPage page = _controller!.document.pageAtIndex(i);
    List<CPDFAnnotation> pageAnnotations = await page.getAnnotations();
    annotations.addAll(pageAnnotations);
  }
}

Using CPDFDocument to Access Annotations

This is ideal for background or logic-only use cases where no UI component is needed.

dart
// Create and open the document
CPDFDocument document = await CPDFDocument.createInstance();
CPDFDocumentError error = await document.open(pdfFilePath);

if (error == CPDFDocumentError.success) {
  List<CPDFAnnotation> annotations = [];

  int pageCount = await document.getPageCount();

  for (int i = 0; i < pageCount; i++) {
    CPDFPage page = document.pageAtIndex(i);
    List<CPDFAnnotation> pageAnnotations = await page.getAnnotations();
    annotations.addAll(pageAnnotations);
  }

  // 'annotations' now contains all annotations from all pages in the document
}