5 Easy Ways to Find Text in PDF Documents in Flutter | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (172).NET Core  (29).NET MAUI  (192)Angular  (107)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (40)Black Friday Deal  (1)Blazor  (209)BoldSign  (12)DocIO  (24)Essential JS 2  (106)Essential Studio  (200)File Formats  (63)Flutter  (131)JavaScript  (219)Microsoft  (118)PDF  (80)Python  (1)React  (98)Streamlit  (1)Succinctly series  (131)Syncfusion  (882)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (49)Windows Forms  (61)WinUI  (68)WPF  (157)Xamarin  (161)XlsIO  (35)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (146)Chart  (125)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (62)Development  (613)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (37)Extensions  (22)File Manager  (6)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (488)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (41)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (368)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (30)Visual Studio Code  (17)Web  (577)What's new  (313)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
5 Easy Ways to Find Text in PDF Documents in Flutter

5 Easy Ways to Find Text in PDF Documents in Flutter

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!

Say goodbye to tedious PDF tasks and hello to effortless document processing with Syncfusion's PDF Library.

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

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';

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,
              )
            ],
          ),
        ),
      );
    }
  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.
    //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.
    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.
    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

Explore the wide array of rich features in Syncfusion's PDF Library through step-by-step instructions and best practices.

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.');
}

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.');
}

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

Witness the advanced capabilities of Syncfusion's PDF Library with feature showcases.

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.');
}

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.');
}

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.

Join thousands of developers who rely on Syncfusion for their PDF needs. Experience the difference today!

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!

googleplay.png

Related blogs

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

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed
Scroll To Top