PDF 生成模板编辑器
开源可视化 PDF 生成引擎,支持自定义模板,并提供面向开发者的 API,灵活构建文档生成流程。
在 Flutter SDK 中,ComPDF 提供了 CPDFTextSearcher API,用于在 PDF 文档中搜索指定文本、高亮显示结果,并获取上下文片段。
在执行搜索之前,需要通过 CPDFDocument 获取一个 CPDFTextSearcher 对象:
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 文档中搜索关键字。您可以指定搜索选项,例如是否区分大小写或是否匹配整个单词。
// 在 PDF 文档中搜索关键字
List<CPDFTextRange> results = await searcher.searchText(
'keywords',
searchOptions: CPDFSearchOptions.caseInsensitive, // 搜索选项
);搜索结果将以 CPDFTextRange 列表的形式返回,每个对象表示文档中匹配关键字的位置范围。
搜索选项说明
| 枚举值 | 描述 |
|---|---|
| CPDFSearchOptions.caseInsensitive | 不区分大小写(默认) |
| CPDFSearchOptions.caseSensitive | 区分大小写 |
| CPDFSearchOptions.matchWholeWord | 匹配整个单词 |
// 高亮第一个搜索结果
if (results.isNotEmpty) {
CPDFTextRange range = results[0];
await searcher.selection(range);
}如需重置搜索状态并清空结果:
await searcher.clearSearch();使用 CPDFPage.getText 可以提取指定范围内的文本片段,并可选择性地扩展范围以包含上下文。
// 假设我们已经获取到一个搜索结果
CPDFTextRange range = results[0];
// 扩展范围,在前后各增加 20 个字符
final expandedRange = range.expanded(before: 20, after: 20);
// 从对应页面中获取上下文文本
final contextText = await page.getText(expandedRange);
print("带上下文的文本: $contextText");在 PDF 搜索中,SDK 允许通过 CPDFConfiguration 自定义搜索结果的高亮显示方式。
开发者可以分别配置:
示例代码
CPDFConfiguration(globalConfig: const CPDFGlobalConfig(
search: CPDFSearchConfig(
normalKeyword: CPDFKeywordConfig(
borderColor: Colors.transparent,
fillColor: Color(0x77FFFF00),
),
focusKeyword: CPDFKeywordConfig(
borderColor: Colors.transparent,
fillColor: Color(0xCCFD7338),
),
)
))在CPDFReaderWidget隐藏了顶部的工具栏情况下,可通过API显示、隐藏搜索视图
// 显示搜索视图
await controller.showTextSearchView();
// 隐藏搜索视图
await controller.hideTextSearchView();