5 Easy Ways to Find Text in PDF Documents in Flutter
Tags: dart, flutter, mobile, pdf
Published: 2021-03-04 13:18:02

---
title: 5 Easy Ways to Find Text in PDF Documents in Flutter
published: true
date: 2021-03-04 12:57:25 UTC
tags: dart, flutter, mobile, PDF
canonical_url: https://www.syncfusion.com/blogs/post/5-easy-ways-to-find-text-in-pdf-documents-in-flutter.aspx
cover_image: https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/5-Easy-Ways-to-Find-Text-in-PDF-Documents-in-Flutter-672x372.png
---

In my previous blog, we discussed [five easy ways to extract text from a PDF document](https://dev.to/syncfusion/5-ways-to-extract-text-from-pdf-documents-in-flutter-3k85 "Link to blog titled 5 ways to extract text from PDF documents in Flutter") using Syncfusion [Flutter PDF Library](https://www.syncfusion.com/flutter-widgets/pdf-library "Link to Syncfusion PDF library"). In this blog, I will walk you through five easy ways to find text in PDF documents in Flutter.

PDF is one of the most popular file formats used to exchange business data since content can’t be modified as easily as in other formats. This safeguards our data from unauthorized modifications. PDF Library does make it easy to _find_ particular text in a PDF document, though, which will help us read and validate data in the PDF in an automated way.

In this blog, we are going to cover the procedures to:

  - [Find and highlight text in a PDF document in Flutter](#find-and-highlight-text-in-a-pdf-document).
  - [Find the text on a specific PDF page in Flutter](#find-the-text-in-a-specific-page).
  - [Find text in a specific range of PDF pages in Flutter](#find-text-in-a-specific-range-of-pdf-pages).
  - [Find text with search options in PDF](#find-text-with-search-options).
  - [Find multiple pieces of text at the same time in PDF](#find-multiple-pieces-of-text-at-the-same-time).

Let’s talk about them with appropriate code examples!

## Find and highlight text in a PDF document in Flutter

We can find each and every instance of a piece of text in an entire PDF document along with its bounds and page indexes. To do this, we need to use the **PdfTextExtractor** API, available in the Syncfusion Flutter PDF Library.

Here’s the procedure to do so:

### Step #1: Create a Flutter application

Follow the instructions provided in this [Get Started](https://flutter.dev/docs/get-started/test-drive?tab=vscode#create-app "Link to the Flutter documentation to create a Flutter application") documentation to create a basic project in Flutter.

### Step #2: Add the Syncfusion Flutter PDF dependency

Include the [Syncfusion Flutter PDF](https://pub.dev/packages/syncfusion_flutter_pdf/ "Link to Flutter PDF package") package dependency in the **pubspec.yaml** file in your project.

```cmd
dependencies:
  syncfusion_flutter_pdf: ^18.3.50-beta
```

### Step #3: Get the package

Run the following command to get the required packages.

| `$ flutter pub get` |

### Step #4: Import the package

Import the PDF package into your **main.dart** file, as shown in the following code example.

```dart
import 'package:syncfusion_flutter_pdf/pdf.dart';
```

### Step #5: Find and highlight the text in the PDF document

1. Add a Button widget as a child to the container widget, as shown in the following code example.
```dart
@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text(widget.title),
    ),
    body: Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          FlatButton(
            child: Text(
              'Find and highlight',
              style: TextStyle(color: Colors.white),
            ),
            onPressed: _extractText,
            color: Colors.blue,
          )
        ],
      ),
    ),
  );
}
```
2. Then, include the following code in the button click event to find and highlight the instances of the required text in the entire PDF file.
```dart
//Load the existing PDF document.
PdfDocument document =
    PdfDocument(inputBytes: await _readDocumentData('pdf_succinctly.pdf'));
//Create the new instance of the PdfTextExtractor.
PdfTextExtractor extractor = PdfTextExtractor(document);
//Find text from the PDF document
List<MatchedItem> findResult = extractor.findText(['PDF']);
if (findResult.length == 0) {
  document.dispose();
  _showResult('The text is not found');
} else {
  //Highlight the searched text from the document.
  for (int i = 0; i < findResult.length; i++) {
    MatchedItem item = findResult[i];
    //Get page.
    PdfPage page = document.pages[item.pageIndex];
    //Set transparency to the page graphics.
    page.graphics.save();
    page.graphics.setTransparency(0.5);
    //Draw rectangle to highlight the text.
    page.graphics
        .drawRectangle(bounds: item.bounds, brush: PdfBrushes.yellow);
    page.graphics.restore();
  }
 //Save and launch the document.
 final List<int> bytes = document.save();
 //Dispose the document.
 document.dispose();
 //Get the storage folder location using path_provider package.
 final Directory directory = await getApplicationDocumentsDirectory();
 final String path = directory.path;
 final File file = File('$path/output.pdf');
 await file.writeAsBytes(bytes);
 //Launch the file (used open_file package)
 await OpenFile.open('$path/output.pdf');
```
3. Include the following code to read the PDF document from the folder where it is saved. Here, we have named our folder [assets](https://github.com/SyncfusionExamples/Find-text-in-PDF-document-Flutter/tree/master/assets "Link to assets folder in the GitHub repository").
```dart
Future<List<int>> _readDocumentData(String name) async {
final ByteData data = await rootBundle.load('assets/$name');
return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
}
```
4. Include the following code to show the found text.
```dart
void _showResult(String text) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('Find Text'),
content: Scrollbar(
child: SingleChildScrollView(
child: Text(text),
physics: BouncingScrollPhysics(
parent: AlwaysScrollableScrollPhysics()),
),
),
actions: [
FlatButton(
child: Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
});
}
```

By executing the project, each instance of the required text will be highlighted and displayed like in the following screenshot.  
 ![Find and highlight text in a PDF document in Flutter](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Find-and-highlight-text-in-a-PDF-document-in-Flutter.png)

## Find the text on a specific PDF page in Flutter

Sometimes, we don’t want to find the instances of a text in the entire PDF document. We need to find the text in a specific page alone. In that scenario, we need to pass the page index of the specific page, along with the text we want to search, to the findText method.

The following code example illustrates how to find a piece of text in a specific page.

```dart
//Load the existing PDF document.
PdfDocument document =
   PdfDocument(inputBytes: await _readDocumentData('pdf_succinctly.pdf'));
//Create the new instance of the PdfTextExtractor.
PdfTextExtractor extractor = PdfTextExtractor(document);
//Find text from the PDF document with a specific page.
List<MatchedItem> findResult =
    extractor.findText(['PDF'], startPageIndex: 0);
if (findResult.length == 0) {
  document.dispose();
  _showResult('The text is not found');
} else {
  _showResult(findResult.length.toString() + ' matches found.');
}
```

When executing the project, the number of text instances in the specific page will be shown like in the following screenshot.  
 ![Find the text on a specific PDF page in Flutter](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Find-the-text-on-a-specific-PDF-page-in-Flutter.png)

## Find text in a specific range of PDF pages in Flutter

We can also find a piece of text in a range of pages within a PDF document by specifying the start and end page indices to the findText method along with the text we want to search .

The following code example illustrates how to find text in a specific range of pages.

```dart
//Load the existing PDF document.
PdfDocument document =
   PdfDocument(inputBytes: await _readDocumentData('pdf_succinctly.pdf'));
//Create the new instance of the PdfTextExtractor.
PdfTextExtractor extractor = PdfTextExtractor(document);
//Find text from the PDF document with a specific range of pages.
List<MatchedItem> findResult =
    extractor.findText(['PDF'], startPageIndex: 1, endPageIndex: 3);
if (findResult.length == 0) {
  document.dispose();
  _showResult('The text is not found');
} else {
  _showResult(findResult.length.toString() + ' matches found.');
}
```

Executing this code will provide all instances found in the specified page range, like in the following screenshot.  
 ![Find text in a specific range of PDF pages in Flutter](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Find-text-in-a-specific-range-of-PDF-pages-in-Flutter.png)

## Find text with search options in PDF

We can find text with the search options case sensitive, whole word match, or both. To do this, we need to provide the search options along with the search text in the findText method.

The following code example illustrates how to find text with the available search options. Here, we are going to search the text with the case sensitive search option.

```dart
//Load the existing PDF document.
PdfDocument document =
   PdfDocument(inputBytes: await _readDocumentData('pdf_succinctly.pdf'));
//Create the new instance of the PdfTextExtractor.
PdfTextExtractor extractor = PdfTextExtractor(document);
//Find text with text search option.
List<MatchedItem> findResult = extractor.findText(['PDF'],
    startPageIndex: 1,
    endPageIndex: 3,
    searchOption: TextSearchOption.caseSensitive);
if (findResult.length == 0) {
  document.dispose();
  _showResult('The text is not found');
} else {
  _showResult(findResult.length.toString() + ' matches found.');
}
```

By executing the code example, you will get output like in the following screenshot.  
 ![Find text with search options in PDF in Flutter](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Find-text-with-search-options-in-PDF-in-Flutter.png)

## Find multiple pieces of text at the same time in PDF

We can also find more than one piece of text using the Syncfusion Flutter PDF package. To do this, we need to provide the multiple lengths of text to the findText method.

The following code illustrates how to find multiple pieces of text at the same time in a PDF document.

```dart
//Load the existing PDF document.
PdfDocument document =
   PdfDocument(inputBytes: await _readDocumentData('pdf_succinctly.pdf'));
//Create the new instance of the PdfTextExtractor.
PdfTextExtractor extractor = PdfTextExtractor(document);
//Find more than one text length at the same time.
List<MatchedItem> findResult = extractor.findText(['PDF', 'document']);
if (findResult.length == 0) {
  document.dispose();
  _showResult('The text is not found');
} else {
  _showResult(findResult.length.toString() + ' matches found.');
}
```

By executing this code example, you will get output like in the following screenshot.  
 ![Find multiple pieces of text at the same time in PDF](https://www.syncfusion.com/blogs/wp-content/uploads/2021/03/Find-multiple-pieces-of-text-at-the-same-time-in-PDF.png)

## Resource

For more information, you can check out [Find text in PDF document Flutter demo](https://github.com/SyncfusionExamples/Find-text-in-PDF-document-Flutter "Link to the find text in the PDF document in Flutter demo on GitHub").

## Conclusion

In this blog post, we have learned the five different ways to find text in a PDF document in Flutter applications using [Syncfusion Flutter PDF Library](https://www.syncfusion.com/flutter-widgets/pdf-library "Link to the Flutter PDF library"). Take a moment to peruse our [documentation](https://help.syncfusion.com/flutter/pdf/working-with-text-extraction#working-with-find-text), where you’ll find other options and features, all with accompanying code examples.

If you have any questions about these features, please let us know in the comments section below. You can also contact us through our [support forum](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [Direct-Trac](https://www.syncfusion.com/support/directtrac/ "Link to the Syncfusion support system Direct Trac"), or [feedback portal](https://www.syncfusion.com/feedback/pdf "Link to Syncfusion Feedback Portal"). We are always happy to assist you!

If you like this article, we think you would also like the following articles:

- [Easily Create PDF Files Using Syncfusion PDF Library for Flutter](https://dev.to/syncfusion/easily-create-pdf-files-using-syncfusion-pdf-library-for-flutter-l41 "Link to the article Easily Create PDF Files Using Syncfusion PDF Library for Flutter") [Blog]
- [How to Encrypt and Decrypt PDF Files in Flutter](https://dev.to/syncfusion/how-to-encrypt-and-decrypt-pdf-files-in-flutter-5hgp "Link to the article How to Encrypt and Decrypt PDF Files in Flutter") [Blog]
- [How to Create PDF/A Standard Files in Flutter](https://dev.to/syncfusion/how-to-create-pdf-a-standard-files-in-flutter-1ic5 "Link to the article How to Create PDF/A Standard Files in Flutter") [Blog]
- [5 Ways to Extract Text from PDF Documents in Flutter](https://dev.to/syncfusion/5-ways-to-extract-text-from-pdf-documents-in-flutter-3k85 "Link to the article 5 Ways to Extract Text from PDF Documents in Flutter") [Blog]
- _[Flutter Succinctly](https://www.syncfusion.com/ebooks/flutter-succinctly "Link to the eBook Flutter Succinctly")_ [eBook]