Skip to content

文本搜索和选取

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

获取 CPDFTextSearcher 实例

要执行搜索,需先从 CPDFDocument 获取一个 CPDFTextSearcher 对象:

tsx
const pdfReaderRef = useRef<CPDFReaderView>(null);

<CPDFReaderView
  ref={pdfReaderRef}
  document={samplePDF}
/>

const document = pdfReaderRef.current?._pdfDocument;
const textSearcher = document!.textSearcher;

文本搜索

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

tsx
// 在 PDF 文档中搜索关键字
const results = await textSearcher!.searchText('keywords', CPDFSearchOptions.CaseInsensitive);

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

搜索选项说明

枚举值描述
CPDFSearchOptions.CaseInsensitive忽略大小写搜索(默认)
CPDFSearchOptions.CaseSensitive区分大小写搜索
CPDFSearchOptions.MatchWholeWord仅匹配整个单词

选中搜索结果

你可以使用 selection 方法在文档中高亮某个结果:

tsx
// 选中第一个搜索结果
if (results.length > 0) {
  await textSearcher.selection(results[0]);
}

清除搜索结果

要重置搜索状态并清除结果:

tsx
await textSearcher.clearSearch();

获取上下文文本

使用 textSearcher.getText 可以提取某个范围的文本,并可选择扩展范围以包含上下文。

tsx
// 假设我们已有一个搜索结果
const range = results[0];

// 向前扩展 20 个字符,向后扩展 20 个字符
const expandedRange = range.expanded(20, 20);

// 从对应页面中获取上下文文本
const contextText = await textSearcher.getText(expandedRange);
print("包含上下文的文本: $contextText");

设置搜索高亮样式

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

开发者可以分别配置:

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

示例代码

tsx
ComPDFKit.getDefaultConfig({
  global: {
    search: {
      normalKeyword: {
        borderColor: '#00000000',
        fillColor: '#FFFF00AA',
      },
      focusKeyword: {
        borderColor: '#00000000',
        fillColor: '#FFA500AA',
      }
    }
  }
})

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

tsx
// 显示搜索视图
await pdfReaderRef.current?.showSearchTextView();

// 隐藏搜索视图
await pdfReaderRef.current?.hideSearchTextView();