Skip to content

文本搜索和选取

在 ReactNative SDK 中,ComPDFKit 提供了 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");