How to find text in a PDF document using Syncfusion Flutter PDF Library
The Syncfusion® Flutter PDF library allows you to find or extract text from an existing PDF document.
Steps to find the matched text in a PDF document programmatically
- Create a new Flutter application project.
1.1.Open Visual Studio Code (After installing the Dart and Flutter extensions as stated in this setup editor page)
1.2.Click View -> Command Palette…
1.3.Type Flutter and choose Flutter: New Project.
1.4.Enter the project name and press the Enter button.
1.5.Now choose the location of the project.
- Add the following code in your pubspec.yaml file to install the syncfusion® flutter pdf package in your application. It will be automatically downloaded from the pub once you trigger the flutter pub get a comment or Get packages option from the Visual studio code.
dependencies: syncfusion_flutter_pdf: ^19.1.55-beta
Import the following package in your main.dart file.
import 'package:syncfusion_flutter_pdf/pdf.dart';
- Add the following code in lib/main.dart file to create a simple button.
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title!), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( child: Text( 'Find and Highlight the Text', style: TextStyle(color: Colors.white), ), style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( (states) => Colors.blue)), onPressed: _findTextfromPDF, ) ], ), ), ); }
- Use the following code to load an existing PDF document in the Flutter project.
4.1.Add the following code in your pubspec.yaml file.
flutter: # To add assets to your application, add an assets section, like this: assets: - assets/pdf/
4.2.Import the following package in your main.dart file.
import 'package:flutter/services.dart';
4.3.Add the following code in the lib/main.dart file to read the existing PDF document.
Future<List<int>> _readDocumentData(String name) async { final ByteData data = await rootBundle.load('assets/pdf/$name'); return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); }
- Add the following code to the _findTextFromPDF function to find the matched text (‘PDF’) from the PDF document and highlight it programmatically. You can change the text manually in the code to find different texts in the document.
Future<void> _findTextfromPDF() async { //Load the document PdfDocument document = PdfDocument(inputBytes: await _readDocumentData('pdf_succinctly.pdf')); //Find the text and get matched items List<MatchedItem> result = PdfTextExtractor(document).findText(['PDF']); //Highlight the searched text from the document for (int i = 0; i < result.length; i++) { MatchedItem item = result[i]; //Get page. PdfPage page = document.pages[item.pageIndex]; //Set transparency to the page graphics page.graphics.save(); page.graphics.setTransparency(0.5); //Draw a rectangle to highlight the text page.graphics .drawRectangle(bounds: item.bounds, brush: PdfBrushes.yellow); page.graphics.restore(); } //Save and dispose the document List<int> bytes = document.save(); //Dispose the document document.dispose(); }
5.1.You can also search for more than one text at the same time by specifying multiple text in the input like the following sample.
//Find the text and get matched items List<MatchedItem> result = PdfTextExtractor(document).findText(['PDF', 'Document', 'table']);
- Use the following code to save and launch the generated PDF file.
6.1.Add the following dependencies in your pubspec.yaml file.
path_provider: ^2.0.1 open_file: ^3.1.0 #Open source library to launch the PDF file in mobile devices
6.2.Import the following packages in your main.dart file.
import 'dart:io'; import 'package:path_provider/path_provider.dart'; import 'package:open_file/open_file.dart';
6.3.Include the following code snippet in the _findTextFromPDF method to open the PDF document in the mobile‘s default application (any PDF Viewer).
//Get an external storage directory Directory directory = (await getApplicationDocumentsDirectory())!; //Get the directory path String path = directory.path; //Create an empty file to write the PDF data File file = File('$path/output.pdf'); //Write the PDF data await file.writeAsBytes(bytes, flush: true); //Open the PDF document in mobile OpenFile.open('$path/output.pdf');
- Run the sample using the flutter run command. This will find the matched text from the document. After the application launches, you will get the PDF document as follows.
A complete working sample can be downloaded from FindTextSample.zip.
Take a moment to peruse the documentation, where you can find other options like extract text and extract text with bounds . Also, the features like headers and footers, bookmarks, tables, hyperlink, annotation PDF documents, and more with code examples.