本页内容
获取注释
要获取 PDF 中的所有注释,需要按照以下步骤操作:
基本流程:
- 获取文档对象(
CPDFReaderWidget
的控制器或CPDFDocument
实例)。 - 获取页面总数,以便遍历每一页。
- 逐页获取页面对象(
CPDFPage
)。 - 从页面对象中获取注释列表。
- 遍历并收集所有页面的注释对象。
使用 CPDFReaderWidget
获取注释
适用于 Flutter UI 集成组件场景。你需要先获取 CPDFReaderWidgetController
,再通过文档对象访问页面和注释。
dart
CPDFReaderWidgetController? _controller;
// 初始化 CPDFReaderWidget,并在 onCreated 回调中获取 controller
CPDFReaderWidget(
document: widget.documentPath,
password: widget.password,
configuration: widget.configuration,
onCreated: (controller) {
setState(() {
_controller = controller;
});
},
);
// 获取注释列表
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);
}
}
使用 CPDFDocument
获取注释
适用于纯逻辑或后台处理场景(无需 UI 组件)。
dart
// 创建并打开文档
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 现在包含了文档中所有页面的注释对象
}