Skip to content

文本搜索和选取

在 Flutter SDK 中,ComPDF 提供了 CPDFTextSearcher API,用于在 PDF 文档中搜索指定文本、高亮显示结果,并获取上下文片段。

获取 CPDFTextSearcher 实例

在执行搜索之前,需要通过 CPDFDocument 获取一个 CPDFTextSearcher 对象:

dart
late CPDFReaderWidgetController _controller;

Scaffold(
  resizeToAvoidBottomInset: false,
  body: CPDFReaderWidget(
    document: widget.documentPath,
    configuration: CPDFConfiguration(),
    onCreated: (controller) {
      setState(() {
        _controller = controller;
      });
    },
  ));

CPDFTextSearcher? textSearcher = _controller?.document.getTextSearcher();

文本搜索

使用 searchText 方法可以在 PDF 文档中搜索关键字。您可以指定搜索选项,例如是否区分大小写或是否匹配整个单词。

dart
// 在 PDF 文档中搜索关键字
List<CPDFTextRange> results = await searcher.searchText(
  'keywords',
  searchOptions: CPDFSearchOptions.caseInsensitive, // 搜索选项
);

搜索结果将以 CPDFTextRange 列表的形式返回,每个对象表示文档中匹配关键字的位置范围。

搜索选项说明

枚举值描述
CPDFSearchOptions.caseInsensitive不区分大小写(默认)
CPDFSearchOptions.caseSensitive区分大小写
CPDFSearchOptions.matchWholeWord匹配整个单词

选择搜索结果

dart
// 高亮第一个搜索结果
if (results.isNotEmpty) {
  CPDFTextRange range = results[0];
  await searcher.selection(range);
}

清除搜索结果

如需重置搜索状态并清空结果:

dart
await searcher.clearSearch();

获取上下文文本

使用 CPDFPage.getText 可以提取指定范围内的文本片段,并可选择性地扩展范围以包含上下文。

dart
// 假设我们已经获取到一个搜索结果
CPDFTextRange range = results[0];

// 扩展范围,在前后各增加 20 个字符
final expandedRange = range.expanded(before: 20, after: 20);

// 从对应页面中获取上下文文本
final contextText = await page.getText(expandedRange);
print("带上下文的文本: $contextText");

设置搜索高亮样式

在 PDF 搜索中,SDK 允许通过 CPDFConfiguration 自定义搜索结果的高亮显示方式。

开发者可以分别配置:

  • 普通匹配结果(normalKeyword):显示所有匹配到的候选文本,仅支持Android平台。
  • 当前选中结果(focusKeyword):突出显示用户正在定位的搜索结果。

示例代码

dart
CPDFConfiguration(globalConfig: const CPDFGlobalConfig(
  search: CPDFSearchConfig(
    normalKeyword: CPDFKeywordConfig(
      borderColor: Colors.transparent,
      fillColor: Color(0x77FFFF00),
    ),
    focusKeyword: CPDFKeywordConfig(
      borderColor: Colors.transparent,
      fillColor: Color(0xCCFD7338),
    ),
  )
))

CPDFReaderWidget隐藏了顶部的工具栏情况下,可通过API显示、隐藏搜索视图

dart
// 显示搜索视图
await controller.showTextSearchView();

// 隐藏搜索视图
await controller.hideTextSearchView();