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!
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:
Follow the instructions provided in this Get Started documentation to create a basic project in Flutter.
Include the Syncfusion Flutter PDF package dependency in the pubspec.yaml file in your project.
dependencies: syncfusion_flutter_pdf: ^18.3.50-beta
Run the following command to get the required packages.
$ flutter pub get |
Import the PDF package into your main.dart file, as shown in the following code example.
import 'package:syncfusion_flutter_pdf/pdf.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, ) ], ), ), ); }
//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');
Future<List<int>> _readDocumentData(String name) async { final ByteData data = await rootBundle.load('assets/$name'); return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); }
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.
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.
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.
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.
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.
For more information, you can check out Find text in PDF document Flutter demo.
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: