DEV Community

loading...
Cover image for 5 Easy Ways to Find Text in PDF Documents in Flutter
Syncfusion, Inc.

5 Easy Ways to Find Text in PDF Documents in Flutter

Suresh Mohan
Suresh is a Product Manager at Syncfusion and a technology enthusiast. He helps people follow best practices in coding and in using Syncfusion controls in their applications.
Originally published at syncfusion.com on ・8 min read

In my previous blog, we discussed five easy ways to extract text from a PDF document using Syncfusion Flutter 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:

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 documentation to create a basic project in Flutter.

Step #2: Add the Syncfusion Flutter PDF dependency

Include the Syncfusion Flutter PDF package dependency in the pubspec.yaml file in your project.

dependencies:
  syncfusion_flutter_pdf: ^18.3.50-beta
Enter fullscreen mode Exit fullscreen mode

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.

import 'package:syncfusion_flutter_pdf/pdf.dart';
Enter fullscreen mode Exit fullscreen mode

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.
@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,
          )
        ],
      ),
    ),
  );
}
Enter fullscreen mode Exit fullscreen mode
  1. 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.
//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');
Enter fullscreen mode Exit fullscreen mode
  1. Include the following code to read the PDF document from the folder where it is saved. Here, we have named our folder assets.
Future<List<int>> _readDocumentData(String name) async {
final ByteData data = await rootBundle.load('assets/$name');
return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
}
Enter fullscreen mode Exit fullscreen mode
  1. Include the following code to show the found text.
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();
},
)
],
);
});
}
Enter fullscreen mode Exit fullscreen mode

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

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.

//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.');
}
Enter fullscreen mode Exit fullscreen mode

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

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.

//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.');
}
Enter fullscreen mode Exit fullscreen mode

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

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.

//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.');
}
Enter fullscreen mode Exit fullscreen mode

By executing the code example, you will get output like in the following screenshot.

Find text with search options in PDF in Flutter

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.

//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.');
}
Enter fullscreen mode Exit fullscreen mode

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

Resource

For more information, you can check out Find text in PDF document Flutter demo.

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. Take a moment to peruse our documentation, 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, Direct-Trac, or feedback portal. We are always happy to assist you!

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

Discussion (0)