Skip to content

Text Search

Takashi Kawasaki edited this page Dec 12, 2024 · 2 revisions

TextSearcher is just a helper class that helps you to implement text searching feature on your app.

The following fragment illustrates the overall usage of the TextSearcher:

class _MainPageState extends State<MainPage> {
  final controller = PdfViewerController();
  // create a PdfTextSearcher and add a listener to update the GUI on search result changes
  late final textSearcher = PdfTextSearcher(controller)..addListener(_update);

  void _update() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void dispose() {
    // dispose the PdfTextSearcher
    textSearcher.removeListener(_update);
    textSearcher.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Pdfrx example'),
      ),
      body: PdfViewer.asset(
        'assets/hello.pdf',
        controller: controller,
        params: PdfViewerParams(
          // add pageTextMatchPaintCallback that paints search hit highlights
          pagePaintCallbacks: [
            textSearcher.pageTextMatchPaintCallback
          ],
        ),
      )
    );
  }
  ...
}

On the fragment above, it does:

Then, you can use TextSearcher.startTextSearch to search text in the PDF document:

textSearcher.startTextSearch('hello', caseInsensitive: true);

The search starts running in background and the search progress is notified by the listener.

There are several functions that helps you to navigate user to the search matches:

You can get the search result (even during the search running) in the list of PdfTextRange by PdfTextSearcher.matches:

for (final match in textSearcher.matches) {
  print(match.pageNumber);
  ...
}

You can also cancel the background search:

textSearcher.resetTextSearch();