{"id":355,"date":"2026-10-30T07:57:00","date_gmt":"2026-10-30T07:57:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=355"},"modified":"2026-11-06T08:47:57","modified_gmt":"2026-11-06T08:47:57","slug":"android-ml-kit-ocr-document-scanner-with-kotlin-jetpack-compose-build-a-searchable-pdf-scanner","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/android-ml-kit-ocr-document-scanner-with-kotlin-jetpack-compose-build-a-searchable-pdf-scanner\/","title":{"rendered":"Android ML Kit OCR + Document Scanner with Kotlin &#038; Jetpack Compose: Build a Searchable PDF Scanner"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Scanning paper documents into PDF files is useful, but finding information inside those documents can still be difficult.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine having hundreds of scanned invoices, receipts, contracts, certificates, and handwritten notes. Without text recognition, you might need to open each PDF individually to find a particular word, amount, or document reference.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">What if users could search their scanned documents simply by entering a keyword?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, searching for <strong>&#8220;Electricity Bill&#8221;<\/strong> could instantly display every scanned document containing those words.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We can build this experience using <strong>Google ML Kit Document Scanner, ML Kit Text Recognition (OCR), Room Database, Kotlin, and Jetpack Compose<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll develop a searchable document scanner that captures documents, extracts text from scanned pages, indexes the recognized content, and displays matching documents.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll also explore MVVM architecture, Room full-text search, secure PDF storage, OCR performance, offline functionality, and production best practices.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. What Are OCR and Searchable PDF Scanning?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">OCR stands for <strong>Optical Character Recognition<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It converts visible text in images into machine-readable text.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, a scanned receipt might contain:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>MOIKS OFFICE SUPPLIES\n\nInvoice: INV-2026-105\n\nKeyboard       \u20b91,500\nMouse            \u20b9800\n\nTotal           \u20b92,300<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">OCR extracts the recognized text so the application can store, search, copy, or analyze it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A searchable document scanner combines document capture with OCR and a search index.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important distinction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">There are two different meanings of searchable PDF scanning:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li><strong>Searchable document library:<\/strong> OCR text is stored separately in a database, allowing the application to find matching PDF files.<\/li>\n\n\n\n<li><strong>Text-searchable PDF:<\/strong> The PDF itself contains a searchable text layer aligned with the scanned page images.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">This tutorial implements the first approach: <strong>a searchable PDF document library<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Adding an embedded text layer to exported PDFs requires a separate PDF-generation or modification workflow, which we&#8217;ll discuss later.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">2. Why Combine ML Kit Document Scanner and OCR?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit provides two complementary APIs.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>Document Scanner<\/th><th>Text Recognition<\/th><\/tr><tr><td>Camera-based document capture<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>Automatic document cropping<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>Image enhancement<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>Multi-page scanning<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>PDF output<\/td><td>Yes<\/td><td>No<\/td><\/tr><tr><td>Extract text from images<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Recognize text blocks and lines<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Search documents<\/td><td>Requires indexing<\/td><td>Provides searchable text<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Combining these APIs produces a practical document management workflow.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">3. Application Features<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Our application will support:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Scan paper documents.<\/li>\n\n\n\n<li>Automatically crop and enhance pages.<\/li>\n\n\n\n<li>Import existing document images.<\/li>\n\n\n\n<li>Generate multi-page PDFs.<\/li>\n\n\n\n<li>Extract text from each scanned page.<\/li>\n\n\n\n<li>Store OCR text locally.<\/li>\n\n\n\n<li>Search saved documents by keywords.<\/li>\n\n\n\n<li>Display matching document results.<\/li>\n\n\n\n<li>Open scanned PDFs.<\/li>\n\n\n\n<li>Rename documents.<\/li>\n\n\n\n<li>Delete documents.<\/li>\n\n\n\n<li>Share documents.<\/li>\n\n\n\n<li>Work offline after required components are available.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The initial implementation will use the Latin-script OCR model.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Additional supported script models can be integrated later.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">4. Application Architecture<\/h2>\n\n\n\n<pre class=\"wp-block-preformatted\"> <code>                Jetpack Compose\n                        |\n                        v\n                 Scanner Screen\n                        |\n                        v\n               ML Kit Document Scanner\n                        |\n              +---------+---------+\n              |                   |\n              v                   v\n          PDF Output          JPEG Pages\n              |                   |\n              v                   v\n       Private File Storage   ML Kit OCR\n              |                   |\n              |                   v\n              |             Recognized Text\n              |                   |\n              +---------+---------+\n                        |\n                        v\n                 Room Database\n                        |\n                        v\n                Full-Text Search\n                        |\n                        v\n                Search Results UI\n                        |\n                        v\n                   PDF Preview<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The application saves the PDF and its OCR text separately.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This keeps document storage independent from text indexing.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">5. Project Requirements<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Recommended technologies:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Component<\/th><th>Technology<\/th><\/tr><tr><td>Programming language<\/td><td>Kotlin<\/td><\/tr><tr><td>UI framework<\/td><td>Jetpack Compose<\/td><\/tr><tr><td>UI design<\/td><td>Material 3<\/td><\/tr><tr><td>Architecture<\/td><td>MVVM<\/td><\/tr><tr><td>Document scanning<\/td><td>ML Kit Document Scanner<\/td><\/tr><tr><td>OCR<\/td><td>ML Kit Text Recognition v2<\/td><\/tr><tr><td>Database<\/td><td>Room<\/td><\/tr><tr><td>Full-text indexing<\/td><td>SQLite FTS4<\/td><\/tr><tr><td>Asynchronous processing<\/td><td>Kotlin Coroutines<\/td><\/tr><tr><td>State management<\/td><td>StateFlow<\/td><\/tr><tr><td>Dependency injection<\/td><td>Hilt<\/td><\/tr><tr><td>PDF preview<\/td><td>Android PdfRenderer<\/td><\/tr><tr><td>Minimum SDK<\/td><td>API 23<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit Text Recognition v2 requires Android API 23 or above.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Document Scanner has additional Google Play services and device-memory requirements.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">6. Create the Android Project<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create a new Empty Activity project.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Project Name: SmartPDFScanner\n\nPackage Name:\ncom.moiks.smartpdfscanner\n\nLanguage: Kotlin\n\nUI: Jetpack Compose\n\nMinimum SDK: 23\n\nArchitecture: MVVM<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use a compatible Kotlin and Compose toolchain.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">7. Add Required Dependencies<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Open <code>app\/build.gradle.kts<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>dependencies {\n\n    \/\/ ML Kit Document Scanner\n    implementation(\n        \"com.google.android.gms:\" +\n        \"play-services-mlkit-document-scanner:16.0.0\"\n    )\n\n    \/\/ Bundled Latin-script OCR model\n    implementation(\n        \"com.google.mlkit:text-recognition:16.0.1\"\n    )\n\n    \/\/ Room Database\n    implementation(\n        \"androidx.room:room-runtime:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.room:room-ktx:&lt;version&gt;\"\n    )\n\n    ksp(\n        \"androidx.room:room-compiler:&lt;version&gt;\"\n    )\n\n    \/\/ Coroutines + Google Tasks\n    implementation(\n        \"org.jetbrains.kotlinx:\" +\n        \"kotlinx-coroutines-play-services:&lt;version&gt;\"\n    )\n\n    \/\/ Compose and Lifecycle\n    implementation(\n        \"androidx.activity:activity-compose:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:\" +\n        \"lifecycle-viewmodel-compose:&lt;version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:\" +\n        \"lifecycle-runtime-compose:&lt;version&gt;\"\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Replace placeholders with compatible stable versions and configure the KSP Gradle plugin.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The bundled OCR model is available immediately after installation. The Document Scanner components are delivered through Google Play services and may require an initial download.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">8. Configure Document Scanner Options<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll request both PDF and JPEG outputs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The PDF is saved as the document.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The JPEG pages are used for OCR.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val scannerOptions =\n    GmsDocumentScannerOptions.Builder()\n        .setGalleryImportAllowed(true)\n        .setPageLimit(20)\n        .setResultFormats(\n            GmsDocumentScannerOptions.RESULT_FORMAT_PDF,\n            GmsDocumentScannerOptions.RESULT_FORMAT_JPEG\n        )\n        .setScannerMode(\n            GmsDocumentScannerOptions.SCANNER_MODE_FULL\n        )\n        .build()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why request both formats?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">PDF output is convenient for document storage and sharing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">JPEG output allows ML Kit Text Recognition to analyze each page without first rendering the PDF.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This reduces implementation complexity.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">9. Initialize the Document Scanner<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>val scanner =\n    GmsDocumentScanning.getClient(\n        scannerOptions\n    )<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner uses a Google-provided interface for capturing and editing documents.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Your application does not need to implement its own camera preview.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">10. Launch the Scanner with Activity Result APIs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Jetpack Compose can launch the scanner through <code>rememberLauncherForActivityResult()<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ScanDocumentButton(\n    onResult: (\n        pdfUri: Uri,\n        pageUris: List&lt;Uri&gt;,\n        pageCount: Int\n    ) -&gt; Unit,\n    onError: (String) -&gt; Unit\n) {\n    val activity =\n        LocalContext.current as? Activity\n\n    val options = remember {\n        GmsDocumentScannerOptions.Builder()\n            .setGalleryImportAllowed(true)\n            .setPageLimit(20)\n            .setResultFormats(\n                GmsDocumentScannerOptions.RESULT_FORMAT_PDF,\n                GmsDocumentScannerOptions.RESULT_FORMAT_JPEG\n            )\n            .setScannerMode(\n                GmsDocumentScannerOptions.SCANNER_MODE_FULL\n            )\n            .build()\n    }\n\n    val scanner = remember(options) {\n        GmsDocumentScanning.getClient(options)\n    }\n\n    val launcher =\n        rememberLauncherForActivityResult(\n            ActivityResultContracts\n                .StartIntentSenderForResult()\n        ) { activityResult -&gt;\n\n            if (\n                activityResult.resultCode ==\n                Activity.RESULT_OK\n            ) {\n                val result =\n                    GmsDocumentScanningResult\n                        .fromActivityResultIntent(\n                            activityResult.data\n                        )\n\n                val pdf = result?.pdf\n\n                if (pdf == null) {\n                    onError(\"PDF was not generated\")\n                    return@rememberLauncherForActivityResult\n                }\n\n                val pages =\n                    result.pages\n                        ?.map { it.imageUri }\n                        .orEmpty()\n\n                onResult(\n                    pdf.uri,\n                    pages,\n                    pdf.pageCount\n                )\n            }\n        }\n\n    Button(\n        onClick = {\n            val currentActivity = activity\n\n            if (currentActivity == null) {\n                onError(\"Activity unavailable\")\n                return@Button\n            }\n\n            scanner.getStartScanIntent(\n                currentActivity\n            ).addOnSuccessListener { intentSender -&gt;\n\n                val request =\n                    IntentSenderRequest.Builder(\n                        intentSender\n                    ).build()\n\n                runCatching {\n                    launcher.launch(request)\n                }.onFailure {\n                    onError(\n                        \"Unable to launch scanner\"\n                    )\n                }\n\n            }.addOnFailureListener {\n                onError(\n                    \"Document scanner unavailable\"\n                )\n            }\n        }\n    ) {\n        Text(\"Scan Document\")\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In production, add a launching state to prevent duplicate requests and handle user cancellation separately.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">11. Understand Scanner Results<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A successful scan can provide:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val pdfUri = result.pdf?.uri\n\nval pageCount =\n    result.pdf?.pageCount ?: 0\n\nval imageUris =\n    result.pages\n        ?.map { it.imageUri }\n        .orEmpty()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Scanned Document\n    |\n    +-- document.pdf\n    |\n    +-- page_1.jpg\n    |\n    +-- page_2.jpg\n    |\n    +-- page_3.jpg<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">We will process each JPEG page using OCR.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">12. What Is ML Kit Text Recognition v2?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Text Recognition v2 is Google&#8217;s on-device OCR API for extracting text from images.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It can recognize:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Text blocks.<\/li>\n\n\n\n<li>Lines.<\/li>\n\n\n\n<li>Individual elements.<\/li>\n\n\n\n<li>Recognized text.<\/li>\n\n\n\n<li>Bounding boxes.<\/li>\n\n\n\n<li>Corner points.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The API supports Latin, Chinese, Devanagari, Japanese, and Korean script models.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each script requires its corresponding model dependency.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For this tutorial, we&#8217;ll start with Latin-script recognition.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">13. Initialize the OCR Client<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>val recognizer =\n    TextRecognition.getClient(\n        TextRecognizerOptions.DEFAULT_OPTIONS\n    )<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Required imports:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import com.google.mlkit.vision.text.TextRecognition\n\nimport com.google.mlkit.vision.text.latin\n    .TextRecognizerOptions<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The import paths are shown on separate lines for readability; use a single valid import statement for <code>TextRecognizerOptions<\/code> in your Kotlin file.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Reuse the recognizer for multiple pages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Close it after processing is complete.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">14. Create an InputImage from a Scanned Page<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit accepts an <code>InputImage<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a scanned JPEG URI:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val image =\n    InputImage.fromFilePath(\n        context,\n        imageUri\n    )<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Required import:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import com.google.mlkit.vision.common.InputImage<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This converts the image into a format ML Kit can process.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For large pages, account for memory usage during image decoding.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">15. Extract Text from a Single Page<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun recognizePage(\n    context: Context,\n    imageUri: Uri,\n    recognizer: TextRecognizer\n): String {\n\n    val image =\n        InputImage.fromFilePath(\n            context,\n            imageUri\n        )\n\n    val result =\n        recognizer.process(image).await()\n\n    return result.text\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The result contains the recognized text.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Invoice Number: INV-2026-105\n\nDate: 15 October 2026\n\nTotal Amount: \u20b92,300<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Actual OCR accuracy depends on image quality, script, text size, and document layout.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">16. Extract Text from Multiple Pages<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A multi-page PDF may contain several scanned images.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Process them sequentially.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun recognizeDocument(\n    context: Context,\n    pageUris: List&lt;Uri&gt;\n): String {\n\n    val recognizer =\n        TextRecognition.getClient(\n            TextRecognizerOptions.DEFAULT_OPTIONS\n        )\n\n    return try {\n\n        buildString {\n\n            pageUris.forEachIndexed {\n                index, uri -&gt;\n\n                val image =\n                    InputImage.fromFilePath(\n                        context,\n                        uri\n                    )\n\n                val result =\n                    recognizer\n                        .process(image)\n                        .await()\n\n                appendLine(\n                    \"Page ${index + 1}\"\n                )\n\n                appendLine(result.text)\n\n                appendLine()\n            }\n        }\n\n    } finally {\n\n        recognizer.close()\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why sequential processing?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Processing pages one at a time reduces peak memory consumption.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is particularly useful for multi-page documents and lower-memory devices.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For production use, run the workflow from a coroutine on an appropriate dispatcher and avoid blocking the main thread during image preparation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">17. Understand OCR Text Structure<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit provides structured text results.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Text\n |\n +-- TextBlock\n      |\n      +-- Line\n           |\n           +-- Element<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>result.textBlocks.forEach { block -&gt;\n\n    block.lines.forEach { line -&gt;\n\n        Log.d(\n            \"OCR\",\n            line.text\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why is this useful?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Text blocks and lines allow you to build advanced features such as:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Text highlighting.<\/li>\n\n\n\n<li>Copy selected text.<\/li>\n\n\n\n<li>Page-specific search results.<\/li>\n\n\n\n<li>OCR bounding-box overlays.<\/li>\n\n\n\n<li>Document text editing.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">18. Create the Scanned Document Data Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We need to store metadata for each scanned document.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Entity(\n    tableName = \"documents\"\n)\ndata class DocumentEntity(\n\n    @PrimaryKey\n    val id: String,\n\n    val title: String,\n\n    val pdfPath: String,\n\n    val pageCount: Int,\n\n    val extractedText: String,\n\n    val createdAt: Long\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important fields<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>id<\/code>: Unique document identifier.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>title<\/code>: User-friendly document name.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>pdfPath<\/code>: Persistent path to the saved PDF.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>pageCount<\/code>: Number of scanned pages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>extractedText<\/code>: Recognized OCR content.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>createdAt<\/code>: Document creation timestamp.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">19. Save the PDF into Private Storage<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Scanner result URIs should not be treated as permanent storage.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Copy the PDF into your application&#8217;s private directory.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun savePdf(\n    context: Context,\n    sourceUri: Uri,\n    documentId: String\n): File = withContext(Dispatchers.IO) {\n\n    val directory =\n        File(\n            context.filesDir,\n            \"documents\"\n        ).apply {\n            mkdirs()\n        }\n\n    val destination =\n        File(\n            directory,\n            \"$documentId.pdf\"\n        )\n\n    val input =\n        context.contentResolver\n            .openInputStream(sourceUri)\n            ?: throw IOException(\n                \"Unable to read PDF\"\n            )\n\n    input.use { source -&gt;\n\n        destination.outputStream().use {\n            output -&gt;\n\n            source.copyTo(output)\n        }\n    }\n\n    destination\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Security recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Generate safe internal file names.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not use arbitrary user-provided paths.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid storing private documents in publicly accessible directories without user intent.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">20. Create the Room DAO<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Start with a simple document database.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Dao\ninterface DocumentDao {\n\n    @Insert(\n        onConflict = OnConflictStrategy.REPLACE\n    )\n    suspend fun insert(\n        document: DocumentEntity\n    )\n\n    @Query(\n        \"SELECT * FROM documents \" +\n        \"ORDER BY createdAt DESC\"\n    )\n    fun getAllDocuments():\n        Flow&lt;List&lt;DocumentEntity&gt;&gt;\n\n    @Query(\n        \"SELECT * FROM documents \" +\n        \"WHERE id = :id LIMIT 1\"\n    )\n    suspend fun getDocument(\n        id: String\n    ): DocumentEntity?\n\n    @Query(\n        \"DELETE FROM documents WHERE id = :id\"\n    )\n    suspend fun deleteDocument(\n        id: String\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Room provides compile-time SQL query validation and reactive query support.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">21. Create the Room Database<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Database(\n    entities = &#91;\n        DocumentEntity::class\n    ],\n    version = 1,\n    exportSchema = true\n)\nabstract class DocumentDatabase :\n    RoomDatabase() {\n\n    abstract fun documentDao():\n        DocumentDao\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Initialize it using a singleton or dependency injection.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Room.databaseBuilder(\n    applicationContext,\n    DocumentDatabase::class.java,\n    \"document_database\"\n).build()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For production applications, use Hilt or another dependency injection solution to provide a single database instance.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">22. Implement Basic Document Search<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For a small number of documents, Room can use SQL <code>LIKE<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Query(\n    \"\"\"\n    SELECT * FROM documents\n    WHERE title LIKE '%' || :query || '%'\n       OR extractedText LIKE '%' || :query || '%'\n    ORDER BY createdAt DESC\n    \"\"\"\n)\nfun searchDocuments(\n    query: String\n): Flow&lt;List&lt;DocumentEntity&gt;&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Advantages<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Simple implementation.<\/li>\n\n\n\n<li>Easy to understand.<\/li>\n\n\n\n<li>Useful for small document collections.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Limitations<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Potentially slow on large text collections.<\/li>\n\n\n\n<li>No relevance ranking.<\/li>\n\n\n\n<li>Limited token-aware search.<\/li>\n\n\n\n<li>Full scans may be expensive.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">For larger collections, use SQLite Full-Text Search.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">23. What Is SQLite Full-Text Search?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">SQLite Full-Text Search (FTS) is designed for efficient searching across text content.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Room supports FTS-backed entities.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Compared with a basic <code>LIKE<\/code> query, FTS is better suited for indexing large amounts of recognized document text.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A document contains:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Monthly Electricity Bill\nConsumer Number 123456\nPayment Due Date 25 October<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Users can search for terms such as:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>electricity\n\nconsumer\n\npayment<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">FTS searches indexed terms instead of scanning every document&#8217;s complete text for each query.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">24. Create a Room FTS4 Entity<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll create a separate search index.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Fts4\n@Entity(\n    tableName = \"document_search\"\n)\ndata class DocumentSearchEntity(\n\n    @PrimaryKey\n    @ColumnInfo(name = \"rowid\")\n    val rowId: Long,\n\n    val title: String,\n\n    val content: String\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">FTS4 tables use an integer <code>rowid<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Our document metadata uses a string ID.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To connect them, we&#8217;ll introduce a numeric search row ID in the document table.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">25. Update the Document Entity for FTS<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Add a unique numeric identifier.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Entity(\n    tableName = \"documents\",\n    indices = &#91;\n        Index(\n            value = &#91;\"searchRowId\"],\n            unique = true\n        )\n    ]\n)\ndata class DocumentEntity(\n\n    @PrimaryKey\n    val id: String,\n\n    val searchRowId: Long,\n\n    val title: String,\n\n    val pdfPath: String,\n\n    val pageCount: Int,\n\n    val extractedText: String,\n\n    val createdAt: Long\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use a stable unique <code>searchRowId<\/code> generated by your persistence layer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For an existing production database, this schema change requires a Room migration.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For a new tutorial project, you can define this schema before creating the first database version.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">26. Add the FTS Entity to Room<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Database(\n    entities = &#91;\n        DocumentEntity::class,\n        DocumentSearchEntity::class\n    ],\n    version = 1,\n    exportSchema = true\n)\nabstract class DocumentDatabase :\n    RoomDatabase() {\n\n    abstract fun documentDao():\n        DocumentDao\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This version assumes a new database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not reset an existing user&#8217;s database merely to introduce FTS.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">27. Search Documents with FTS4<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create a query that joins the FTS index with document metadata.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Query(\n    \"\"\"\n    SELECT d.*\n    FROM documents AS d\n    JOIN document_search AS s\n      ON d.searchRowId = s.rowid\n    WHERE document_search MATCH :query\n    ORDER BY d.createdAt DESC\n    \"\"\"\n)\nfun searchDocumentsFts(\n    query: String\n): Flow&lt;List&lt;DocumentEntity&gt;&gt;<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">FTS queries use their own query syntax.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not pass arbitrary raw user input directly as an unrestricted FTS expression.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Normalize or safely construct supported search terms before calling the DAO.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">28. Build a Safe Search Query<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">For a basic keyword search, convert user input into quoted terms.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fun buildFtsQuery(\n    input: String\n): String {\n\n    val words =\n        input.trim()\n            .split(Regex(\"\\\\s+\"))\n            .filter { it.isNotBlank() }\n\n    return words.joinToString(\" AND \") {\n        word -&gt;\n\n        val safeWord =\n            word.replace(\"\\\"\", \"\\\"\\\"\")\n\n        \"\\\"$safeWord\\\"\"\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This is a simplified example of constructing an AND query.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Production recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Handle empty input separately.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Define a maximum query length.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Validate query syntax.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Catch malformed-query errors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test punctuation, Unicode text, and non-Latin scripts.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">29. Keep the Search Index Updated<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">When a new document is scanned:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Save the PDF.<\/li>\n\n\n\n<li>Extract OCR text.<\/li>\n\n\n\n<li>Insert document metadata.<\/li>\n\n\n\n<li>Insert FTS content.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">These database writes should occur inside a transaction.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Dao\ninterface DocumentDao {\n\n    @Insert\n    suspend fun insertDocument(\n        document: DocumentEntity\n    )\n\n    @Insert\n    suspend fun insertSearch(\n        search: DocumentSearchEntity\n    )\n\n    @Transaction\n    suspend fun insertWithIndex(\n        document: DocumentEntity,\n        search: DocumentSearchEntity\n    ) {\n        insertDocument(document)\n        insertSearch(search)\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Also update the FTS row when a document is renamed or its OCR text changes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Delete the corresponding FTS row when the document is deleted.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Otherwise, search results may become inconsistent.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">30. Create the Document Repository<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The repository coordinates PDF storage, OCR, and Room.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class DocumentRepository(\n    private val context: Context,\n    private val dao: DocumentDao\n) {\n\n    suspend fun processDocument(\n        pdfUri: Uri,\n        pageUris: List&lt;Uri&gt;,\n        pageCount: Int,\n        searchRowId: Long\n    ) {\n\n        val documentId =\n            UUID.randomUUID().toString()\n\n        val pdfFile =\n            savePdf(\n                context,\n                pdfUri,\n                documentId\n            )\n\n        val recognizedText =\n            recognizeDocument(\n                context,\n                pageUris\n            )\n\n        val title =\n            \"Scan_${System.currentTimeMillis()}\"\n\n        val document =\n            DocumentEntity(\n                id = documentId,\n                searchRowId = searchRowId,\n                title = title,\n                pdfPath = pdfFile.absolutePath,\n                pageCount = pageCount,\n                extractedText = recognizedText,\n                createdAt =\n                    System.currentTimeMillis()\n            )\n\n        val search =\n            DocumentSearchEntity(\n                rowId = searchRowId,\n                title = title,\n                content = recognizedText\n            )\n\n        dao.insertWithIndex(\n            document,\n            search\n        )\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Production improvements<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Generate the numeric search ID inside the persistence layer rather than accepting it from arbitrary callers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Handle PDF cleanup if database insertion fails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Support retrying failed OCR.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Track individual page results.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">31. Handle Partial OCR Failures<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A 20-page document may contain a page that cannot be recognized.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not automatically discard the entire scan because one page fails.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended workflow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Page 1 -&gt; OCR Success\n\nPage 2 -&gt; OCR Success\n\nPage 3 -&gt; OCR Failure\n\nPage 4 -&gt; OCR Success<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Possible result:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>OCR completed for 3 of 4 pages.<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Save the PDF.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Persist successful OCR results.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Mark failed pages for retry.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Display a non-blocking warning.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This improves reliability for large documents.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">32. Create Document UI State<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>data class DocumentUiState(\n\n    val documents:\n        List&lt;DocumentEntity&gt; = emptyList(),\n\n    val searchQuery: String = \"\",\n\n    val isProcessing: Boolean = false,\n\n    val processingPage: Int = 0,\n\n    val totalPages: Int = 0,\n\n    val errorMessage: String? = null\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The UI can display progress while OCR processes pages.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">33. Create the ViewModel<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class DocumentViewModel(\n    private val repository:\n        DocumentRepository\n) : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow(\n            DocumentUiState()\n        )\n\n    val uiState =\n        _uiState.asStateFlow()\n\n    fun updateSearchQuery(\n        query: String\n    ) {\n        _uiState.update {\n            it.copy(\n                searchQuery = query\n            )\n        }\n    }\n\n    fun processScan(\n        pdfUri: Uri,\n        pageUris: List&lt;Uri&gt;,\n        pageCount: Int,\n        searchRowId: Long\n    ) {\n\n        viewModelScope.launch {\n\n            _uiState.update {\n                it.copy(\n                    isProcessing = true,\n                    errorMessage = null\n                )\n            }\n\n            try {\n\n                repository.processDocument(\n                    pdfUri,\n                    pageUris,\n                    pageCount,\n                    searchRowId\n                )\n\n            } catch (\n                error: CancellationException\n            ) {\n                throw error\n\n            } catch (\n                error: Exception\n            ) {\n\n                _uiState.update {\n                    it.copy(\n                        errorMessage =\n                            \"Unable to process document\"\n                    )\n                }\n\n            } finally {\n\n                _uiState.update {\n                    it.copy(\n                        isProcessing = false\n                    )\n                }\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For production, generate IDs inside the repository, expose document flows, and use lifecycle-independent work for scans that must survive process termination.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">34. Build the Jetpack Compose Home Screen<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The main screen should include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Application title.<\/li>\n\n\n\n<li>Search field.<\/li>\n\n\n\n<li>Scan button.<\/li>\n\n\n\n<li>Recent documents.<\/li>\n\n\n\n<li>Processing indicator.<\/li>\n\n\n\n<li>Empty state.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun DocumentHomeScreen(\n    state: DocumentUiState,\n    onSearchChanged: (String) -&gt; Unit,\n    onScanClick: () -&gt; Unit\n) {\n\n    Column(\n        modifier = Modifier\n            .fillMaxSize()\n            .padding(16.dp)\n    ) {\n\n        Text(\n            text = \"Smart PDF Scanner\",\n            style =\n                MaterialTheme.typography\n                    .headlineMedium\n        )\n\n        Spacer(\n            modifier = Modifier.height(16.dp)\n        )\n\n        OutlinedTextField(\n            value = state.searchQuery,\n            onValueChange = onSearchChanged,\n            label = {\n                Text(\"Search documents\")\n            },\n            modifier =\n                Modifier.fillMaxWidth(),\n            singleLine = true\n        )\n\n        Spacer(\n            modifier = Modifier.height(16.dp)\n        )\n\n        Button(\n            onClick = onScanClick,\n            modifier =\n                Modifier.fillMaxWidth()\n        ) {\n            Text(\"Scan New Document\")\n        }\n\n        if (state.isProcessing) {\n\n            LinearProgressIndicator(\n                modifier =\n                    Modifier.fillMaxWidth()\n            )\n        }\n\n        LazyColumn {\n\n            items(\n                state.documents,\n                key = { it.id }\n            ) { document -&gt;\n\n                DocumentCard(document)\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">35. Create Document Cards<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun DocumentCard(\n    document: DocumentEntity\n) {\n\n    ElevatedCard(\n        modifier = Modifier\n            .fillMaxWidth()\n            .padding(vertical = 6.dp)\n    ) {\n\n        Column(\n            modifier =\n                Modifier.padding(16.dp)\n        ) {\n\n            Text(\n                text = document.title,\n                style =\n                    MaterialTheme.typography\n                        .titleMedium\n            )\n\n            Text(\n                text =\n                    \"${document.pageCount} pages\"\n            )\n\n            Text(\n                text =\n                    document.extractedText\n                        .take(120),\n                maxLines = 3,\n                overflow =\n                    TextOverflow.Ellipsis\n            )\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For production, add document thumbnails, file sizes, creation dates, and contextual actions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">36. Add Real-Time Search with Debounce<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Searching on every keystroke may cause unnecessary database queries.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>debounce()<\/code> with StateFlow.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val searchResults =\n    uiState\n        .map { it.searchQuery }\n        .debounce(300)\n        .distinctUntilChanged()\n        .flatMapLatest { query -&gt;\n\n            if (query.isBlank()) {\n\n                dao.getAllDocuments()\n\n            } else {\n\n                dao.searchDocumentsFts(\n                    buildFtsQuery(query)\n                )\n            }\n        }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Responsive search.<\/li>\n\n\n\n<li>Fewer database queries.<\/li>\n\n\n\n<li>Automatic cancellation of outdated searches.<\/li>\n\n\n\n<li>Efficient UI updates.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Use an appropriate <code>stateIn()<\/code> configuration to expose results to Compose.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">37. Highlight Matching Search Terms<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Users should understand why a document matched their search.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Search: electricity\n\nResult:\nElectricity Bill - October\n\nMatched text:\n\"...monthly electricity usage...\"<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended implementation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Store OCR text and, for advanced search, page-specific text.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>AnnotatedString<\/code> to highlight matching words.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For large documents, generate short search snippets rather than displaying the complete OCR text.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">38. Support Page-Specific OCR Results<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of storing all recognized text in one field, introduce a page table.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Entity(\n    tableName = \"document_pages\",\n    primaryKeys = &#91;\n        \"documentId\",\n        \"pageNumber\"\n    ]\n)\ndata class DocumentPageEntity(\n\n    val documentId: String,\n\n    val pageNumber: Int,\n\n    val recognizedText: String\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Benefits<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Search results can identify matching pages.<\/li>\n\n\n\n<li>Failed pages can be retried.<\/li>\n\n\n\n<li>OCR progress can be tracked.<\/li>\n\n\n\n<li>Page-level text can be displayed.<\/li>\n\n\n\n<li>Advanced highlighting becomes possible.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Electricity Bill.pdf\n\nMatch found on Page 3<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">39. Open Scanned PDFs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Android provides <code>PdfRenderer<\/code> for rendering PDF pages.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The application can display a PDF preview using the saved local file.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val descriptor =\n    ParcelFileDescriptor.open(\n        pdfFile,\n        ParcelFileDescriptor.MODE_READ_ONLY\n    )\n\nval renderer =\n    PdfRenderer(descriptor)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Open a page:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val page =\n    renderer.openPage(0)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Render it into a Bitmap with appropriate dimensions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Close the page and renderer after use.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">PDF rendering should be performed off the main thread when it involves expensive work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid keeping all rendered pages in memory.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">40. Share a Saved PDF<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Use <code>FileProvider<\/code> to expose an application-private PDF to another application.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val uri =\n    FileProvider.getUriForFile(\n        context,\n        \"${context.packageName}.fileprovider\",\n        pdfFile\n    )<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Share it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val intent =\n    Intent(Intent.ACTION_SEND).apply {\n\n        type = \"application\/pdf\"\n\n        putExtra(\n            Intent.EXTRA_STREAM,\n            uri\n        )\n\n        addFlags(\n            Intent.FLAG_GRANT_READ_URI_PERMISSION\n        )\n    }\n\ncontext.startActivity(\n    Intent.createChooser(\n        intent,\n        \"Share PDF\"\n    )\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A valid FileProvider declaration and paths XML configuration are required.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not expose raw private file paths.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">41. Can We Create a Truly Searchable PDF?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Yes, but OCR extraction alone is insufficient.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The PDF itself needs an embedded text layer.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Standard workflow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Scanned Page Image\n        |\n        v\nOCR Text Recognition\n        |\n        v\nText + Bounding Boxes\n        |\n        v\nPDF Generation Engine\n        |\n        v\nImage Layer\n        +\nInvisible Text Layer\n        |\n        v\nText-Searchable PDF<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Why bounding boxes matter<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">OCR text must be positioned over the corresponding scanned characters.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Otherwise, text selection and search highlighting may not align correctly.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important implementation challenges<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Coordinate conversion.<\/li>\n\n\n\n<li>Font handling.<\/li>\n\n\n\n<li>Text positioning.<\/li>\n\n\n\n<li>Multi-line layout.<\/li>\n\n\n\n<li>Page rotation.<\/li>\n\n\n\n<li>Text visibility.<\/li>\n\n\n\n<li>Unicode support.<\/li>\n\n\n\n<li>PDF library licensing.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Implement the searchable document library first.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Add embedded PDF text layers as a separate advanced feature.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">42. Add Multiple OCR Script Models<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit Text Recognition v2 supports multiple scripts.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, Devanagari:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>implementation(\n    \"com.google.mlkit:\" +\n    \"text-recognition-devanagari:16.0.1\"\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Chinese:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>implementation(\n    \"com.google.mlkit:\" +\n    \"text-recognition-chinese:16.0.1\"\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Japanese:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>implementation(\n    \"com.google.mlkit:\" +\n    \"text-recognition-japanese:16.0.1\"\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Korean:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>implementation(\n    \"com.google.mlkit:\" +\n    \"text-recognition-korean:16.0.1\"\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important distinction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Devanagari model is suitable for Devanagari-script text such as Hindi.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It does not provide Telugu-script recognition.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not claim Telugu OCR support through the listed ML Kit v2 models.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">43. Offline OCR and Document Scanning<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The bundled OCR model works without downloading an additional OCR model.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">However, Document Scanner uses components delivered through Google Play services.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Offline behavior<\/h3>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Feature<\/th><th>Offline support<\/th><\/tr><tr><td>Bundled Latin OCR<\/td><td>Yes<\/td><\/tr><tr><td>Room document search<\/td><td>Yes<\/td><\/tr><tr><td>Saved PDF preview<\/td><td>Yes<\/td><\/tr><tr><td>Local document history<\/td><td>Yes<\/td><\/tr><tr><td>Document scanning<\/td><td>After required components are available<\/td><\/tr><tr><td>Cloud backup<\/td><td>Requires connectivity<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Explain that first-time scanner setup may require an internet connection.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not promise guaranteed offline scanning on a fresh installation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">44. Performance Optimization<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">OCR performance<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Process pages sequentially.<\/li>\n\n\n\n<li>Reuse the TextRecognizer.<\/li>\n\n\n\n<li>Avoid unnecessary Bitmap copies.<\/li>\n\n\n\n<li>Limit image decoding memory.<\/li>\n\n\n\n<li>Process only changed pages.<\/li>\n\n\n\n<li>Cache successful OCR results.<\/li>\n\n\n\n<li>Close recognition clients properly.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Database performance<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use FTS for large document collections.<\/li>\n\n\n\n<li>Avoid loading complete OCR text into list items.<\/li>\n\n\n\n<li>Paginate large document lists.<\/li>\n\n\n\n<li>Use indexed queries.<\/li>\n\n\n\n<li>Keep database writes transactional.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">PDF performance<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Render pages lazily.<\/li>\n\n\n\n<li>Use thumbnail caching.<\/li>\n\n\n\n<li>Close PdfRenderer resources.<\/li>\n\n\n\n<li>Avoid holding large Bitmaps in ViewModels.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">45. Use WorkManager for Long-Running OCR<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A multi-page document may require more processing time than a short UI operation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For background OCR, consider WorkManager.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended workflow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Document Saved\n       |\n       v\nOCR Work Request\n       |\n       v\nProcess Pages\n       |\n       v\nUpdate Room Database\n       |\n       v\nUpdate Search Index\n       |\n       v\nNotify UI<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Persist the scanned PDF and required page images before scheduling background work.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not pass temporary scanner URIs to a worker if they may become inaccessible later.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For lengthy user-visible processing, use the appropriate foreground-work mechanism and comply with Android&#8217;s background execution requirements.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">46. Privacy and Security<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Scanned documents may contain sensitive information.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Identity documents.<\/li>\n\n\n\n<li>Financial statements.<\/li>\n\n\n\n<li>Medical records.<\/li>\n\n\n\n<li>Business contracts.<\/li>\n\n\n\n<li>Invoices.<\/li>\n\n\n\n<li>Addresses.<\/li>\n\n\n\n<li>Personal correspondence.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Store PDFs privately by default.<\/li>\n\n\n\n<li>Avoid logging OCR text.<\/li>\n\n\n\n<li>Do not upload documents without consent.<\/li>\n\n\n\n<li>Use secure file-sharing mechanisms.<\/li>\n\n\n\n<li>Protect database access.<\/li>\n\n\n\n<li>Provide permanent deletion controls.<\/li>\n\n\n\n<li>Avoid including document text in analytics events.<\/li>\n\n\n\n<li>Consider encryption for sensitive document collections.<\/li>\n\n\n\n<li>Review backup and data-retention behavior.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Extracted OCR text can be as sensitive as the original PDF.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Protect both the document files and the search index.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">47. Testing Strategy<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Test scenario<\/th><th>Expected behavior<\/th><\/tr><tr><td>Single-page scan<\/td><td>PDF saved and OCR completed<\/td><\/tr><tr><td>Multi-page scan<\/td><td>All pages processed<\/td><\/tr><tr><td>Clear printed text<\/td><td>Text extracted<\/td><\/tr><tr><td>Blurry document<\/td><td>Graceful handling<\/td><\/tr><tr><td>Empty document<\/td><td>No crash<\/td><\/tr><tr><td>Handwritten notes<\/td><td>Best-effort OCR<\/td><\/tr><tr><td>Large PDF<\/td><td>Controlled memory usage<\/td><\/tr><tr><td>OCR failure<\/td><td>Retry or partial result<\/td><\/tr><tr><td>Search keyword<\/td><td>Matching documents shown<\/td><\/tr><tr><td>Multiple search terms<\/td><td>Correct FTS behavior<\/td><\/tr><tr><td>Special characters<\/td><td>Safe query handling<\/td><\/tr><tr><td>Document rename<\/td><td>Search index updated<\/td><\/tr><tr><td>Document deletion<\/td><td>PDF and index removed<\/td><\/tr><tr><td>Offline OCR<\/td><td>Works with bundled model<\/td><\/tr><tr><td>Scanner unavailable<\/td><td>Helpful error<\/td><\/tr><tr><td>Device rotation<\/td><td>State retained<\/td><\/tr><tr><td>App restart<\/td><td>Saved documents persist<\/td><\/tr><tr><td>Dark mode<\/td><td>Readable UI<\/td><\/tr><tr><td>Tablet<\/td><td>Adaptive layout<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Additional testing<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Test Room migrations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test FTS index consistency.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test interrupted file writes.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test low-storage conditions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test document-sharing permissions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test long-running OCR and process termination.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">48. Common Development Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Assuming ML Kit Document Scanner Performs OCR<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Document Scanner captures and enhances documents.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Text Recognition extracts text separately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Calling a PDF Searchable Without an Embedded Text Layer<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A searchable document library is not necessarily a text-searchable PDF file.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Using Temporary Scanner URIs Permanently<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Copy files into durable storage.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Processing All Pages Simultaneously<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This can increase memory usage.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Searching Large OCR Text with LIKE<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use FTS when the document library grows.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Ignoring FTS Index Synchronization<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep document metadata and search indexes consistent.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Blocking the Main Thread<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use Coroutines and appropriate dispatchers.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Assuming OCR Is Always Accurate<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Recognition depends on image quality and supported scripts.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Storing Sensitive Text Without Protection<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">OCR text needs the same privacy considerations as PDF files.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Ignoring Background Processing Requirements<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use durable work scheduling for long-running tasks.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">49. Production Checklist<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Before publishing:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Document Scanner dependency configured.<\/li>\n\n\n\n<li>ML Kit OCR dependency configured.<\/li>\n\n\n\n<li>Minimum SDK supported.<\/li>\n\n\n\n<li>Google Play services requirements handled.<\/li>\n\n\n\n<li>PDF and JPEG outputs requested.<\/li>\n\n\n\n<li>Scanner cancellation handled.<\/li>\n\n\n\n<li>Scanned PDFs copied into durable storage.<\/li>\n\n\n\n<li>OCR processes each page.<\/li>\n\n\n\n<li>OCR failures handled.<\/li>\n\n\n\n<li>TextRecognizer lifecycle managed.<\/li>\n\n\n\n<li>Room database configured.<\/li>\n\n\n\n<li>FTS search index implemented.<\/li>\n\n\n\n<li>Search queries validated.<\/li>\n\n\n\n<li>Search index synchronized.<\/li>\n\n\n\n<li>Document history implemented.<\/li>\n\n\n\n<li>PDF preview implemented.<\/li>\n\n\n\n<li>Secure PDF sharing configured.<\/li>\n\n\n\n<li>Document deletion implemented.<\/li>\n\n\n\n<li>Background processing reviewed.<\/li>\n\n\n\n<li>Privacy protections implemented.<\/li>\n\n\n\n<li>Database migrations tested.<\/li>\n\n\n\n<li>Physical devices tested.<\/li>\n\n\n\n<li>Accessibility reviewed.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">50. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is Android ML Kit OCR?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit OCR is Google&#8217;s on-device text recognition technology for extracting text from images.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can ML Kit OCR read scanned PDFs?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit Text Recognition processes images. You can use scanned JPEG pages or render PDF pages into images before recognition.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does ML Kit Document Scanner automatically extract text?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Use Text Recognition separately.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I build a searchable PDF scanner with Kotlin?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Combine Document Scanner, Text Recognition, Room, and Jetpack Compose.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does this tutorial generate PDFs with embedded searchable text?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. It creates a searchable document library by storing OCR text separately from the PDFs.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I add embedded searchable text to PDFs?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes, using a PDF library capable of placing a text layer over scanned page images.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does OCR work offline?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The bundled ML Kit OCR model works offline.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I search thousands of scanned documents?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. SQLite FTS is suitable for efficient text search, with appropriate indexing and pagination.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it support Hindi OCR?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit provides a Devanagari text recognition model, which supports Devanagari-script text.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it support Telugu OCR?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The listed ML Kit Text Recognition v2 script models do not include Telugu.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can it recognize handwriting?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit Text Recognition may recognize some handwriting, but accuracy varies. It is not a guaranteed handwriting transcription solution.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is a backend required?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No backend is required for local scanning, OCR, storage, and search.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I use Jetpack Compose?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Compose provides the application UI, while the Google-provided scanner handles document capture.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should I use Room or SQLite directly?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Room is recommended for maintainable Android persistence.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is OCR text private?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">OCR processing can run on-device, but developers must still protect saved text, PDFs, backups, and sharing workflows.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Combining <strong>Google ML Kit Document Scanner, ML Kit Text Recognition, Room Database, and Jetpack Compose<\/strong> enables Android developers to build intelligent document management applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of simply saving scanned PDFs, the application can recognize text, index document content, and provide fast keyword-based search.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The key implementation practices are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use ML Kit Document Scanner for document capture.<\/li>\n\n\n\n<li>Request both PDF and JPEG outputs.<\/li>\n\n\n\n<li>Extract text from each scanned page.<\/li>\n\n\n\n<li>Process OCR asynchronously.<\/li>\n\n\n\n<li>Save PDFs in durable private storage.<\/li>\n\n\n\n<li>Store recognized text using Room.<\/li>\n\n\n\n<li>Use SQLite FTS for efficient document search.<\/li>\n\n\n\n<li>Keep search indexes synchronized.<\/li>\n\n\n\n<li>Handle partial OCR failures.<\/li>\n\n\n\n<li>Protect sensitive document data.<\/li>\n\n\n\n<li>Use WorkManager when durable background processing is needed.<\/li>\n\n\n\n<li>Distinguish searchable document libraries from PDFs with embedded text layers.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>A well-designed searchable document scanner transforms static scanned files into an organized, searchable collection of information.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This architecture provides a strong foundation for PDF scanner apps, receipt organizers, smart notes, invoice management, and business document utilities.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Official References<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/developers.google.com\/ml-kit\/vision\/doc-scanner\/android\" target=\"_blank\" rel=\"noopener\">ML Kit Document Scanner for Android<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developers.google.com\/ml-kit\/vision\/text-recognition\/v2\/android\" target=\"_blank\" rel=\"noopener\">ML Kit Text Recognition v2 for Android<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developers.google.com\/ml-kit\/release-notes\" target=\"_blank\" rel=\"noopener\">ML Kit Release Notes<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/training\/data-storage\/room\" target=\"_blank\" rel=\"noopener\">Room Database Documentation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/training\/data-storage\/room\/defining-data\" target=\"_blank\" rel=\"noopener\">Room Entities and Full-Text Search<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/develop\/ui\/compose\" target=\"_blank\" rel=\"noopener\">Jetpack Compose Documentation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/reference\/android\/graphics\/pdf\/PdfRenderer\" target=\"_blank\" rel=\"noopener\">Android PdfRenderer<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/topic\/libraries\/architecture\/workmanager\" target=\"_blank\" rel=\"noopener\">Android WorkManager<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/reference\/androidx\/core\/content\/FileProvider\" target=\"_blank\" rel=\"noopener\">Android FileProvider<\/a><\/li>\n<\/ul>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Published by Moiks Developer Blog \u2014 Practical tutorials covering Android, Kotlin, Jetpack Compose, Flutter, React Native, SwiftUI, and modern software engineering.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Build a smart Android document scanner using Google ML Kit Document Scanner, Text Recognition, Kotlin, and Jetpack Compose. Capture multi-page PDFs, extract text with on-device OCR, store documents and recognized text using Room, and search your scanned document library. Learn MVVM architecture, PDF previews, full-text indexing, secure storage, performance optimization, and production best practices.<\/p>\n","protected":false},"author":1,"featured_media":356,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":0,"footnotes":""},"categories":[16,3,333,6,5],"tags":[255,248,254,28,26,247,62,253,252],"class_list":["post-355","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-advanced-android","category-android-development","category-android-tutorials","category-jetpack-compose","category-kotlin","tag-android-ml-kit-ocr","tag-android-pdf-scanner","tag-full-text-search","tag-jetpack-compose","tag-kotlin","tag-ml-kit-document-scanner","tag-room-database","tag-searchable-pdf-scanner","tag-text-recognition"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/355","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/comments?post=355"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/355\/revisions"}],"predecessor-version":[{"id":357,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/355\/revisions\/357"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/356"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=355"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=355"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=355"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}