{"id":352,"date":"2026-10-30T03:30:00","date_gmt":"2026-10-30T03:30:00","guid":{"rendered":"https:\/\/moiks.com\/blog\/?p=352"},"modified":"2026-11-06T08:47:58","modified_gmt":"2026-11-06T08:47:58","slug":"android-ml-kit-document-scanner-with-kotlin-jetpack-compose-build-a-pdf-scanning-app","status":"publish","type":"post","link":"https:\/\/moiks.com\/blog\/android-ml-kit-document-scanner-with-kotlin-jetpack-compose-build-a-pdf-scanning-app\/","title":{"rendered":"Android ML Kit Document Scanner with Kotlin &#038; Jetpack Compose: Build a PDF Scanning App"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">Document scanning is one of the most useful features in modern Android productivity applications.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Users frequently need to digitize receipts, invoices, handwritten notes, certificates, business documents, and printed forms.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A traditional document scanner application requires several complex components, including camera integration, document boundary detection, perspective correction, image enhancement, page management, and PDF generation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Fortunately, <strong>Google ML Kit Document Scanner<\/strong> provides a ready-made document scanning experience that handles much of this complexity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The API offers a Google-provided scanning interface with automatic document detection, cropping, image enhancements, multi-page scanning, and PDF\/JPEG output.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In this tutorial, we&#8217;ll integrate ML Kit Document Scanner into a Kotlin and Jetpack Compose application, handle scanning results, display scanned pages, save PDF files, and implement sharing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll also discuss MVVM architecture, secure storage, Google Play services requirements, error handling, testing, 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 Is Google ML Kit Document Scanner?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit Document Scanner is an Android API that provides a complete document scanning workflow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of building a custom camera scanner, developers launch a Google-provided scanning interface.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner can capture physical documents and return processed image and PDF files to the application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Key features<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Automatic document detection.<\/li>\n\n\n\n<li>Document edge and corner detection.<\/li>\n\n\n\n<li>Perspective correction.<\/li>\n\n\n\n<li>Automatic cropping.<\/li>\n\n\n\n<li>Image enhancement and filters.<\/li>\n\n\n\n<li>Multi-page document scanning.<\/li>\n\n\n\n<li>Optional gallery import.<\/li>\n\n\n\n<li>JPEG output.<\/li>\n\n\n\n<li>PDF output.<\/li>\n\n\n\n<li>Google-provided scanner interface.<\/li>\n\n\n\n<li>On-device scanning and processing.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner UI is provided by Google Play services rather than implemented manually with Jetpack Compose.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">2. Why Use ML Kit Document Scanner?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Building a document scanner from scratch is challenging.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A custom solution typically requires:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>CameraX integration.<\/li>\n\n\n\n<li>Camera lifecycle management.<\/li>\n\n\n\n<li>Image capture.<\/li>\n\n\n\n<li>Edge detection algorithms.<\/li>\n\n\n\n<li>Perspective transformation.<\/li>\n\n\n\n<li>Image processing.<\/li>\n\n\n\n<li>Document cropping.<\/li>\n\n\n\n<li>PDF creation.<\/li>\n\n\n\n<li>Device-specific camera handling.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit Document Scanner handles the capture and processing workflow.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Advantages<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Faster development:<\/strong> Integrate a scanner without implementing camera algorithms.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Consistent user experience:<\/strong> Use a standardized scanner interface.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Reduced permissions:<\/strong> No camera permission is required by the host application for the ML Kit scanning workflow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Multi-page support:<\/strong> Capture several pages in one scanning session.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>PDF generation:<\/strong> Receive a PDF directly from the scanner.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Smaller integration footprint:<\/strong> The SDK adds approximately 300 KB to the application download, while its implementation is delivered through Google Play services.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">3. Real-World Applications<\/h2>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Application<\/th><th>Scanner use case<\/th><\/tr><tr><td>PDF Scanner<\/td><td>Scan documents into PDF<\/td><\/tr><tr><td>Expense Tracker<\/td><td>Capture receipts<\/td><\/tr><tr><td>Notes Application<\/td><td>Scan handwritten notes<\/td><\/tr><tr><td>Document Organizer<\/td><td>Digitize certificates<\/td><\/tr><tr><td>Business Application<\/td><td>Capture invoices<\/td><\/tr><tr><td>Educational Application<\/td><td>Scan study materials<\/td><\/tr><tr><td>Inventory Application<\/td><td>Capture paper records<\/td><\/tr><tr><td>Productivity Utility<\/td><td>Save and share documents<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">A document scanner can also be integrated as a feature inside an existing application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">4. How ML Kit Document Scanner Works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The complete workflow:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>User Taps Scan Document\n          |\n          v\nJetpack Compose Screen\n          |\n          v\nML Kit Document Scanner\n          |\n          v\nGoogle-Provided Camera UI\n          |\n          v\nDocument Detection\n          |\n          v\nCrop and Enhance\n          |\n          v\nMulti-Page Preview\n          |\n          v\nUser Confirms Scan\n          |\n          v\nActivity Result\n          |\n          +-- JPEG Page URIs\n          |\n          +-- PDF URI\n          |\n          v\nAndroid Application\n          |\n          v\nPreview \/ Save \/ Share<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important architectural detail<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner UI is external to your Compose layout.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Your application controls when scanning starts and what happens after the result is returned.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">5. Project Requirements<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Recommended configuration:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Android Studio.<\/li>\n\n\n\n<li>Kotlin.<\/li>\n\n\n\n<li>Jetpack Compose.<\/li>\n\n\n\n<li>Material 3.<\/li>\n\n\n\n<li>MVVM architecture.<\/li>\n\n\n\n<li>Activity Result APIs.<\/li>\n\n\n\n<li>Google Play services.<\/li>\n\n\n\n<li>Minimum Android API 21.<\/li>\n\n\n\n<li>Device RAM of at least 1.7 GB.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Google documents the Android API 21 and 1.7 GB RAM requirements.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Devices below the supported memory requirement can return an <code>UNSUPPORTED<\/code> ML Kit error.<\/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 an Empty Activity project.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Project Name: DocumentScanner\n\nPackage Name: com.moiks.documentscanner\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\">Although the scanner supports API 21, using API 23 as the minimum for a new application is a reasonable project choice.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">7. Add the ML Kit Document Scanner Dependency<\/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    implementation(\n        \"com.google.android.gms:\" +\n            \"play-services-mlkit-document-scanner:16.0.0\"\n    )\n\n    implementation(\n        \"androidx.activity:activity-compose:&lt;stable-version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:lifecycle-viewmodel-compose:&lt;stable-version&gt;\"\n    )\n\n    implementation(\n        \"androidx.lifecycle:lifecycle-runtime-compose:&lt;stable-version&gt;\"\n    )\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Replace the AndroidX placeholders with compatible stable versions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Ensure the project includes Google&#8217;s Maven repository.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>repositories {\n    google()\n    mavenCentral()\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The document scanner SDK is distributed through Google Play services.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It is not the same as the bundled ML Kit text-recognition library.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">8. Understand Scanner Modes<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit provides three scanner modes.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><tbody><tr><th>Scanner mode<\/th><th>Functionality<\/th><\/tr><tr><td>SCANNER_MODE_BASE<\/td><td>Basic document scanning<\/td><\/tr><tr><td>SCANNER_MODE_BASE_WITH_FILTER<\/td><td>Basic scanning with image filters<\/td><\/tr><tr><td>SCANNER_MODE_FULL<\/td><td>Full scanner features, including additional image cleanup capabilities<\/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\">Use <code>SCANNER_MODE_FULL<\/code> for a document scanner application when you want the richest supported editing experience.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The exact available UI features can depend on the Google Play services implementation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">9. Configure Scanner Options<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create a scanner configuration.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val options =\n    GmsDocumentScannerOptions.Builder()\n        .setGalleryImportAllowed(true)\n        .setPageLimit(20)\n        .setResultFormats(\n            GmsDocumentScannerOptions.RESULT_FORMAT_JPEG,\n            GmsDocumentScannerOptions.RESULT_FORMAT_PDF\n        )\n        .setScannerMode(\n            GmsDocumentScannerOptions.SCANNER_MODE_FULL\n        )\n        .build()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>setGalleryImportAllowed(true)<\/code> enables importing images from the gallery.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>setPageLimit(20)<\/code> limits the number of pages in a scanning session.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>setResultFormats()<\/code> requests JPEG page images and a PDF document.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>setScannerMode()<\/code> selects the scanning feature set.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For an initial version, support 10\u201320 pages per session.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test memory usage and file sizes before increasing the limit.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">10. Initialize the Document Scanner<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Create a scanner client.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val scanner =\n    GmsDocumentScanning.getClient(options)<\/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.documentscanner.GmsDocumentScanning\nimport com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner provides an intent sender that launches the document scanning workflow.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">11. Understand Activity Result Integration<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Modern Android applications should use the Activity Result API rather than the deprecated <code>startActivityForResult()<\/code> pattern.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For document scanning, use:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ActivityResultContracts.StartIntentSenderForResult()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner returns its result after the user completes or cancels the scanning process.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Result states<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Successful scan.<\/li>\n\n\n\n<li>User cancellation.<\/li>\n\n\n\n<li>Scanner failure.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Handle these states separately.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">12. Launch the Scanner from Jetpack Compose<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The following example demonstrates the core integration.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun DocumentScannerLauncher(\n    onScanCompleted: (Uri?, List&lt;Uri&gt;) -&gt; Unit,\n    onError: (String) -&gt; Unit\n) {\n    val context = LocalContext.current\n\n    val activity = context as? Activity\n\n    val options = remember {\n        GmsDocumentScannerOptions.Builder()\n            .setGalleryImportAllowed(true)\n            .setPageLimit(20)\n            .setResultFormats(\n                GmsDocumentScannerOptions.RESULT_FORMAT_JPEG,\n                GmsDocumentScannerOptions.RESULT_FORMAT_PDF\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            contract =\n                ActivityResultContracts\n                    .StartIntentSenderForResult()\n        ) { activityResult -&gt;\n\n            if (activityResult.resultCode == Activity.RESULT_OK) {\n\n                val result =\n                    GmsDocumentScanningResult\n                        .fromActivityResultIntent(\n                            activityResult.data\n                        )\n\n                if (result == null) {\n                    onError(\"No scan result received\")\n                    return@rememberLauncherForActivityResult\n                }\n\n                val pdfUri =\n                    result.pdf?.uri\n\n                val imageUris =\n                    result.pages\n                        ?.map { it.imageUri }\n                        .orEmpty()\n\n                onScanCompleted(\n                    pdfUri,\n                    imageUris\n                )\n            }\n        }\n\n    Button(\n        onClick = {\n\n            if (activity == null) {\n                onError(\"Activity unavailable\")\n                return@Button\n            }\n\n            scanner.getStartScanIntent(activity)\n                .addOnSuccessListener { intentSender -&gt;\n\n                    val request =\n                        IntentSenderRequest.Builder(\n                            intentSender\n                        ).build()\n\n                    launcher.launch(request)\n                }\n                .addOnFailureListener { error -&gt;\n\n                    onError(\n                        error.message\n                            ?: \"Unable to start scanner\"\n                    )\n                }\n        }\n    ) {\n        Text(\"Scan Document\")\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important considerations<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A production implementation should also handle:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>User cancellation.<\/li>\n\n\n\n<li>Scanner availability.<\/li>\n\n\n\n<li>Loading states.<\/li>\n\n\n\n<li>Rapid repeated taps.<\/li>\n\n\n\n<li>Exceptions when launching the intent sender.<\/li>\n\n\n\n<li>Activity lifecycle changes.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">13. Understand the Scan Result<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit returns a <code>GmsDocumentScanningResult<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The result may contain:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Scanned JPEG pages.<\/li>\n\n\n\n<li>A generated PDF.<\/li>\n\n\n\n<li>PDF page count.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The available outputs depend on the configured result formats.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>val result =\n    GmsDocumentScanningResult\n        .fromActivityResultIntent(data)\n\nval pages = result?.pages\n\nval pdf = result?.pdf<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Do not assume both formats are always available.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">14. Get Scanned JPEG Pages<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Each scanned page contains an image URI.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val imageUris =\n    result?.pages\n        ?.map { page -&gt;\n            page.imageUri\n        }\n        .orEmpty()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">These URIs can be used to display document thumbnails or previews.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do not load all full-resolution images into memory simultaneously.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use efficient image loading and thumbnail decoding.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">15. Get the Generated PDF<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">If PDF output was requested:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>val pdf = result?.pdf\n\nval pdfUri = pdf?.uri\n\nval pageCount = pdf?.pageCount ?: 0<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important distinction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit already generates the PDF.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You do not need to manually convert every scanned image into a PDF unless your application requires custom layouts or additional processing.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">16. Create a Scanned Document Model<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Keep scanner-specific APIs separate from your application state.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data class ScannedDocument(\n    val id: String,\n    val pdfUri: Uri?,\n    val pageUris: List&lt;Uri&gt;,\n    val pageCount: Int,\n    val createdAt: Long\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>Easier ViewModel management.<\/li>\n\n\n\n<li>Simpler UI rendering.<\/li>\n\n\n\n<li>Better testability.<\/li>\n\n\n\n<li>Support for document history.<\/li>\n\n\n\n<li>Future Room integration.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Scanner output URIs should not automatically be treated as permanent storage.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Copy files into an appropriate application-owned location when long-term retention is required.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">17. Create Document Scanner UI State<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>data class DocumentScannerUiState(\n    val isLaunchingScanner: Boolean = false,\n    val isSaving: Boolean = false,\n    val document: ScannedDocument? = null,\n    val errorMessage: String? = null\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This state model separates scanning, saving, results, and errors.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">18. Create the Scanner ViewModel<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>class DocumentScannerViewModel : ViewModel() {\n\n    private val _uiState =\n        MutableStateFlow(\n            DocumentScannerUiState()\n        )\n\n    val uiState = _uiState.asStateFlow()\n\n    fun setLaunching(launching: Boolean) {\n\n        _uiState.update {\n            it.copy(\n                isLaunchingScanner = launching\n            )\n        }\n    }\n\n    fun onScanCompleted(\n        pdfUri: Uri?,\n        imageUris: List&lt;Uri&gt;,\n        pageCount: Int\n    ) {\n\n        val document =\n            ScannedDocument(\n                id = UUID.randomUUID().toString(),\n                pdfUri = pdfUri,\n                pageUris = imageUris,\n                pageCount = pageCount,\n                createdAt =\n                    System.currentTimeMillis()\n            )\n\n        _uiState.update {\n            it.copy(\n                isLaunchingScanner = false,\n                document = document,\n                errorMessage = null\n            )\n        }\n    }\n\n    fun onScanError(message: String) {\n\n        _uiState.update {\n            it.copy(\n                isLaunchingScanner = false,\n                errorMessage = message\n            )\n        }\n    }\n\n    fun clearError() {\n\n        _uiState.update {\n            it.copy(errorMessage = null)\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Architecture recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Keep the Activity Result launcher in the Activity or Compose UI layer.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The ViewModel should receive scan results rather than directly own Android activity-launching APIs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">19. Build a Premium Document Scanner Screen<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Suggested UI layout:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>+--------------------------------+\n|         Document Scanner       |\n|                                |\n|     Scan Documents to PDF      |\n|                                |\n|       &#91; Scan Document ]        |\n|                                |\n|--------------------------------|\n|                                |\n|       Recently Scanned         |\n|                                |\n|  +----------+  +----------+    |\n|  | Page 1   |  | Page 2   |    |\n|  | Preview  |  | Preview  |    |\n|  +----------+  +----------+    |\n|                                |\n|  Document_2026.pdf             |\n|  2 Pages                       |\n|                                |\n|  &#91;Save PDF]    &#91;Share]          |\n+--------------------------------+<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">UI recommendations<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use Material 3.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Provide a prominent Scan Document button.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Display page thumbnails.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Show the PDF page count.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Offer Save and Share actions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Support dark and light themes.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">20. Create a Document Preview Card<\/h2>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ScannedDocumentCard(\n    document: ScannedDocument\n) {\n    ElevatedCard(\n        modifier = Modifier.fillMaxWidth()\n    ) {\n\n        Column(\n            modifier = Modifier.padding(16.dp),\n            verticalArrangement =\n                Arrangement.spacedBy(8.dp)\n        ) {\n\n            Text(\n                text = \"Scanned Document\",\n                style =\n                    MaterialTheme.typography.titleLarge\n            )\n\n            Text(\n                text = \"${document.pageCount} pages\"\n            )\n\n            Text(\n                text = \"PDF available: \" +\n                    (document.pdfUri != null)\n            )\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For a production application, add:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Document thumbnail.<\/li>\n\n\n\n<li>File name.<\/li>\n\n\n\n<li>File size.<\/li>\n\n\n\n<li>Scan date.<\/li>\n\n\n\n<li>Rename action.<\/li>\n\n\n\n<li>Save button.<\/li>\n\n\n\n<li>Share button.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">21. Display Scanned Page Thumbnails<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">You can use an image-loading library such as Coil to display JPEG URIs.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ScannedPageThumbnail(\n    imageUri: Uri\n) {\n    AsyncImage(\n        model = imageUri,\n        contentDescription = \"Scanned page\",\n        modifier = Modifier\n            .fillMaxWidth()\n            .height(240.dp),\n        contentScale = ContentScale.Fit\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Add the compatible Coil Compose dependency.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use thumbnail sizing and caching to avoid decoding full-resolution pages unnecessarily.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">22. Display Multiple Scanned Pages<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Use a LazyRow or LazyVerticalGrid.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun ScannedPagesRow(\n    imageUris: List&lt;Uri&gt;\n) {\n    LazyRow(\n        horizontalArrangement =\n            Arrangement.spacedBy(12.dp),\n        contentPadding =\n            PaddingValues(16.dp)\n    ) {\n\n        items(imageUris) { uri -&gt;\n\n            Box(\n                modifier = Modifier.width(160.dp)\n            ) {\n                ScannedPageThumbnail(uri)\n            }\n        }\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">For large documents, show a grid with page numbers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Allow users to tap a page for full-screen preview.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">23. Save the PDF Using Storage Access Framework<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The Storage Access Framework allows users to choose where to save their scanned PDF.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>ActivityResultContracts.CreateDocument(\n    \"application\/pdf\"\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This approach avoids requesting broad storage permissions.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Compose example<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>@Composable\nfun SavePdfButton(\n    sourcePdfUri: Uri\n) {\n    val context = LocalContext.current\n\n    val launcher =\n        rememberLauncherForActivityResult(\n            contract =\n                ActivityResultContracts.CreateDocument(\n                    \"application\/pdf\"\n                )\n        ) { destinationUri -&gt;\n\n            if (destinationUri != null) {\n\n                runCatching {\n\n                    context.contentResolver\n                        .openInputStream(sourcePdfUri)\n                        ?.use { input -&gt;\n\n                            context.contentResolver\n                                .openOutputStream(destinationUri)\n                                ?.use { output -&gt;\n\n                                    input.copyTo(output)\n                                }\n                        }\n                }\n            }\n        }\n\n    Button(\n        onClick = {\n            launcher.launch(\n                \"Scanned_Document.pdf\"\n            )\n        }\n    ) {\n        Text(\"Save PDF\")\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Production improvement<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Perform file copying on <code>Dispatchers.IO<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Check that both streams open successfully.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Report copy failures to the user.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid performing large file operations on the main thread.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">24. Save Scans to App-Specific Storage<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Another option is to save the PDF in your application&#8217;s private files directory.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>suspend fun savePdfToAppStorage(\n    context: Context,\n    sourceUri: Uri,\n    fileName: String\n): File = withContext(Dispatchers.IO) {\n\n    val directory =\n        File(\n            context.filesDir,\n            \"scanned_documents\"\n        ).apply {\n            mkdirs()\n        }\n\n    val destination =\n        File(directory, fileName)\n\n    context.contentResolver\n        .openInputStream(sourceUri)\n        ?.use { input -&gt;\n\n            destination.outputStream().use { output -&gt;\n                input.copyTo(output)\n            }\n        }\n        ?: throw IOException(\n            \"Unable to open source PDF\"\n        )\n\n    destination\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important security consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Validate generated file names.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid using untrusted paths directly.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">App-specific storage is appropriate for private document history.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">25. Share Scanned PDFs<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To share a PDF URI:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fun sharePdf(\n    context: Context,\n    pdfUri: Uri\n) {\n    val intent =\n        Intent(Intent.ACTION_SEND).apply {\n\n            type = \"application\/pdf\"\n\n            putExtra(\n                Intent.EXTRA_STREAM,\n                pdfUri\n            )\n\n            addFlags(\n                Intent.FLAG_GRANT_READ_URI_PERMISSION\n            )\n        }\n\n    context.startActivity(\n        Intent.createChooser(\n            intent,\n            \"Share scanned PDF\"\n        )\n    )\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The URI must be accessible to the receiving application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For PDFs saved as private files, expose them through a correctly configured FileProvider rather than using <code>file:\/\/<\/code> URIs.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">26. Handle Scanner Cancellation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Users may close the scanner without completing a scan.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is normal behavior.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>when (activityResult.resultCode) {\n\n    Activity.RESULT_OK -&gt; {\n        \/\/ Process scan.\n    }\n\n    Activity.RESULT_CANCELED -&gt; {\n        \/\/ User canceled.\n    }\n\n    else -&gt; {\n        \/\/ Handle unexpected result.\n    }\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">UX recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Do not display an error dialog when the user intentionally cancels.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Return to the previous screen gracefully.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">27. Handle Unsupported Devices<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">ML Kit Document Scanner requires a supported Google Play services environment.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It also requires at least 1.7 GB of total device RAM.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">On unsupported devices, the API may return an <code>MlKitException<\/code> with an <code>UNSUPPORTED<\/code> error code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Display:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&#8220;Document scanning is not supported on this device.&#8221;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Offer another import method when appropriate.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not assume every Android device supports the Google-provided scanner.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">28. Understand Google Play Services Requirements<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The document scanner implementation is delivered dynamically through Google Play services.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What this means<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Initial scanning may require downloading components.<\/li>\n\n\n\n<li>The first launch may take longer.<\/li>\n\n\n\n<li>Network connectivity may be needed for initial setup.<\/li>\n\n\n\n<li>The scanner is not guaranteed to work on devices without the required Google Play services support.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important distinction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner processes documents on-device, but its components may require an initial download.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not advertise guaranteed first-launch offline scanning.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">29. Add Gallery Import<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Enable gallery import using:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>.setGalleryImportAllowed(true)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This allows users to import existing images through the scanner interface.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended use cases<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Previously captured receipts.<\/li>\n\n\n\n<li>Screenshots of documents.<\/li>\n\n\n\n<li>Saved forms.<\/li>\n\n\n\n<li>Existing document photographs.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Privacy advantage<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner can handle gallery selection without requiring broad media-library access from the host application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">30. Understand Automatic Document Detection<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner can detect document edges and corners.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This improves scanning quality when users photograph documents at an angle.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Typical workflow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Camera Preview\n      |\n      v\nDocument Boundary Detection\n      |\n      v\nPerspective Correction\n      |\n      v\nCropped Document<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important limitation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Detection quality depends on lighting, contrast, document condition, and camera quality.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Users should still be able to review the scanned result.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">31. Understand Image Enhancement<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner supports image enhancement and filters according to the selected scanner mode.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Potential improvements include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Contrast enhancement.<\/li>\n\n\n\n<li>Color adjustments.<\/li>\n\n\n\n<li>Document cleanup.<\/li>\n\n\n\n<li>Perspective correction.<\/li>\n\n\n\n<li>Stain or blemish reduction.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use the full scanner mode when you want the richest available editing experience.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let users review the processed document before saving.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">32. Multi-Page PDF Scanning<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A useful scanner should support several pages in one document.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Page 1: Invoice\n\nPage 2: Invoice Details\n\nPage 3: Payment Information<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner can return one PDF containing all pages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Implementation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Configure:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>.setPageLimit(20)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">And request:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>.setResultFormats(\n    GmsDocumentScannerOptions.RESULT_FORMAT_PDF\n)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recommendation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use the returned PDF directly rather than reconstructing it unnecessarily from JPEG pages.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">33. Add Document Renaming<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Users should be able to choose descriptive document names.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Examples:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Electricity_Bill_October.pdf\n\nOffice_Invoice_2026.pdf\n\nProject_Notes.pdf\n\nTravel_Receipts.pdf<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended behavior<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Provide a default name.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Allow editing before saving.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Sanitize file names.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid duplicate-name conflicts.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">34. Add Recent Document History<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">A production scanner can maintain a history of saved documents.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Suggested model:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>data class DocumentHistoryItem(\n    val id: String,\n    val title: String,\n    val localPath: String,\n    val pageCount: Int,\n    val createdAt: Long\n)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Use Room to store document metadata.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended features<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Recent scans.<\/li>\n\n\n\n<li>Search documents.<\/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>Sort by date.<\/li>\n\n\n\n<li>Sort by name.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Store durable document paths or identifiers, not temporary scanner URIs that may expire.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">35. Add PDF Preview<\/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\">A PDF preview screen can display:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Individual pages.<\/li>\n\n\n\n<li>Page numbers.<\/li>\n\n\n\n<li>Zoom controls.<\/li>\n\n\n\n<li>Scrollable previews.<\/li>\n\n\n\n<li>Document information.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><code>PdfRenderer<\/code> requires a seekable file descriptor.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Depending on the URI provider, you may need to copy the PDF into a suitable local file first.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Close the renderer and its underlying file descriptor when finished.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">36. Add OCR as an Optional Feature<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Document scanning and OCR are different technologies.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Document Scanner:<\/strong> Captures and processes document images.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Text Recognition:<\/strong> Extracts readable text from images.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To build a searchable document scanner, combine ML Kit Document Scanner with ML Kit Text Recognition.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Workflow<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>Document Scanner\n       |\n       v\nScanned JPEG Pages\n       |\n       v\nML Kit Text Recognition\n       |\n       v\nExtracted Text\n       |\n       v\nSearchable Document Metadata<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Important distinction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Document Scanner API does not automatically provide extracted OCR text.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A PDF returned by the scanner should not be assumed to contain a searchable text layer.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">37. Recommended MVVM Architecture<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Suggested project structure:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>com.moiks.documentscanner\/\n|\n+-- data\/\n|   +-- scanner\/\n|   |   +-- DocumentRepository.kt\n|   |\n|   +-- storage\/\n|   |   +-- PdfStorageManager.kt\n|   |   +-- DocumentFileProvider.kt\n|   |\n|   +-- local\/\n|       +-- DocumentDao.kt\n|       +-- DocumentDatabase.kt\n|\n+-- domain\/\n|   +-- model\/\n|   |   +-- ScannedDocument.kt\n|   |   +-- DocumentHistoryItem.kt\n|   |\n|   +-- usecase\/\n|       +-- SaveScannedDocumentUseCase.kt\n|       +-- DeleteDocumentUseCase.kt\n|\n+-- presentation\/\n|   +-- DocumentScannerViewModel.kt\n|   +-- DocumentScannerUiState.kt\n|\n+-- ui\/\n|   +-- DocumentScannerScreen.kt\n|   +-- DocumentPreviewScreen.kt\n|   +-- ScannedPageThumbnail.kt\n|   +-- DocumentHistoryScreen.kt\n|\n+-- MainActivity.kt<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Responsibilities<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Compose UI:<\/strong> Launches scanner and displays results.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>ViewModel:<\/strong> Manages document state.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Repository:<\/strong> Coordinates document operations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Storage Manager:<\/strong> Saves PDF and JPEG files.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Room:<\/strong> Stores persistent metadata.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>UseCases:<\/strong> Encapsulate business logic.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">38. Performance Optimization<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Best practices<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Avoid decoding full-resolution images unnecessarily.<\/li>\n\n\n\n<li>Use thumbnail loading.<\/li>\n\n\n\n<li>Perform file operations on background dispatchers.<\/li>\n\n\n\n<li>Reuse existing PDFs instead of recreating them.<\/li>\n\n\n\n<li>Limit unnecessary memory allocations.<\/li>\n\n\n\n<li>Release PDF renderers.<\/li>\n\n\n\n<li>Avoid retaining large Bitmaps in ViewModels.<\/li>\n\n\n\n<li>Use LazyColumn or LazyVerticalGrid for document history.<\/li>\n\n\n\n<li>Test multi-page scanning on lower-memory devices.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Important consideration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Large scanned documents may produce substantial PDF and JPEG files.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Measure file sizes and storage consumption on real devices.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">39. 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 documents.<\/li>\n\n\n\n<li>Contracts.<\/li>\n\n\n\n<li>Certificates.<\/li>\n\n\n\n<li>Personal addresses.<\/li>\n\n\n\n<li>Business invoices.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Recommended practices<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Store documents privately by default.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid uploading files without user consent.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not log document contents.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Use FileProvider for controlled sharing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Grant temporary URI access.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Avoid broad storage permissions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Provide document deletion controls.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Explain how scanned files are stored and shared.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Important distinction<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">On-device scanning does not automatically secure files after they are saved or shared.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">40. 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 document<\/td><td>Successful scan<\/td><\/tr><tr><td>Multi-page document<\/td><td>Correct page count<\/td><\/tr><tr><td>PDF output<\/td><td>Valid PDF URI<\/td><\/tr><tr><td>JPEG output<\/td><td>Valid page URIs<\/td><\/tr><tr><td>Gallery import<\/td><td>Image selection works<\/td><\/tr><tr><td>Scanner cancellation<\/td><td>Graceful return<\/td><\/tr><tr><td>Low-light document<\/td><td>User can review result<\/td><\/tr><tr><td>Angled document<\/td><td>Crop and correction<\/td><\/tr><tr><td>Model download required<\/td><td>Loading handled<\/td><\/tr><tr><td>No network on first launch<\/td><td>Helpful failure handling<\/td><\/tr><tr><td>Offline after setup<\/td><td>Supported workflow tested<\/td><\/tr><tr><td>Unsupported device<\/td><td>Clear error<\/td><\/tr><tr><td>Save PDF<\/td><td>File written correctly<\/td><\/tr><tr><td>Share PDF<\/td><td>Receiver can open file<\/td><\/tr><tr><td>Large PDF<\/td><td>No UI freezing<\/td><\/tr><tr><td>Device rotation<\/td><td>State handled<\/td><\/tr><tr><td>Dark theme<\/td><td>Readable UI<\/td><\/tr><tr><td>Tablet<\/td><td>Responsive layout<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h3 class=\"wp-block-heading\">Additional tests<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Verify that exported PDFs open in multiple PDF viewers.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Check that files remain accessible after app restart.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test repeated scans.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test storage-full conditions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Test interrupted file copying.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">41. Common Document Scanner Mistakes<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 1: Requesting Camera Permission Unnecessarily<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The ML Kit scanner workflow does not require your application to request camera permission.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 2: Assuming All Devices Are Supported<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Google Play services and hardware requirements apply.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 3: Assuming the Scanner Works Offline on First Launch<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Initial components may require downloading.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 4: Recreating the PDF Unnecessarily<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The scanner can return a ready-made PDF.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 5: Keeping Only Temporary URIs<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Copy important documents into durable storage.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 6: Blocking the Main Thread During File Copying<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use Dispatchers.IO.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 7: Loading Full-Resolution Pages into Memory<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use efficient thumbnail loading.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 8: Sharing Private File Paths Directly<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Use content URIs and appropriate grants.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 9: Assuming the PDF Contains OCR Text<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Document scanning and text recognition are separate operations.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Mistake 10: Ignoring Cancellation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">User cancellation is not an application error.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">42. 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>ML Kit Document Scanner dependency is configured.<\/li>\n\n\n\n<li>Minimum SDK is supported.<\/li>\n\n\n\n<li>Google Play services requirements are understood.<\/li>\n\n\n\n<li>Unsupported devices are handled.<\/li>\n\n\n\n<li>Scanner modes are configured.<\/li>\n\n\n\n<li>Gallery import is configured.<\/li>\n\n\n\n<li>Page limits are configured.<\/li>\n\n\n\n<li>PDF output is enabled.<\/li>\n\n\n\n<li>JPEG output is enabled if needed.<\/li>\n\n\n\n<li>Activity Result integration works.<\/li>\n\n\n\n<li>Cancellation is handled.<\/li>\n\n\n\n<li>Scanner errors are handled.<\/li>\n\n\n\n<li>PDF files are saved safely.<\/li>\n\n\n\n<li>Temporary URIs are not used as permanent references.<\/li>\n\n\n\n<li>Sharing uses content URI permissions.<\/li>\n\n\n\n<li>PDF previews work.<\/li>\n\n\n\n<li>Document history works if implemented.<\/li>\n\n\n\n<li>Storage-full conditions are handled.<\/li>\n\n\n\n<li>Privacy protections are implemented.<\/li>\n\n\n\n<li>16 KB page-size compatibility is verified.<\/li>\n\n\n\n<li>Physical Android devices are tested.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">43. Frequently Asked Questions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">What is ML Kit Document Scanner?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">It is Google&#8217;s Android document scanning API that provides document capture, cropping, enhancement, and PDF\/JPEG output.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it require camera permission?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. The Google-provided scanning workflow does not require camera permission from the host application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it support PDF generation?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. It can return a PDF containing scanned pages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it support multiple pages?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Developers can configure the maximum number of pages.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it support gallery import?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Gallery import can be enabled through scanner options.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it automatically crop documents?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. The scanning experience includes document detection and cropping capabilities.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it support image filters?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Available enhancement capabilities depend on the scanner mode.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it work offline?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Scanning can work after the required components are available, but the initial Google Play services download may require connectivity.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it require a backend?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No backend is required for basic document scanning.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I use it with Jetpack Compose?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Launch the scanner using the Activity Result API from a Compose application.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it support Android 5.0?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The documented minimum is Android API 21, subject to Google Play services and device requirements.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I build a PDF scanner application with it?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. The API provides the core scanning workflow needed for a PDF scanner.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Does it extract text automatically?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. Use a separate OCR API such as ML Kit Text Recognition for extracted text.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Can I store scanned PDFs locally?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. Use app-specific storage or the Storage Access Framework.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is it suitable for production apps?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes, provided you handle supported devices, scanner availability, file storage, sharing, privacy, and release compatibility.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Google ML Kit Document Scanner significantly simplifies document scanning development on Android.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of implementing a custom camera pipeline, document boundary detection, perspective correction, image enhancement, and PDF generation, developers can integrate Google&#8217;s scanning workflow.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By combining ML Kit Document Scanner with Kotlin, Jetpack Compose, Activity Result APIs, and MVVM architecture, we can build a practical document scanning application with a modern interface.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The most important practices are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the official ML Kit Document Scanner dependency.<\/li>\n\n\n\n<li>Configure scanner modes and output formats.<\/li>\n\n\n\n<li>Launch scanning through Activity Result APIs.<\/li>\n\n\n\n<li>Handle cancellation and unsupported devices.<\/li>\n\n\n\n<li>Retrieve JPEG pages and PDF output.<\/li>\n\n\n\n<li>Save documents into durable storage.<\/li>\n\n\n\n<li>Share files using content URIs.<\/li>\n\n\n\n<li>Perform file operations off the main thread.<\/li>\n\n\n\n<li>Use efficient image previews.<\/li>\n\n\n\n<li>Protect sensitive scanned documents.<\/li>\n\n\n\n<li>Add OCR separately when searchable text is required.<\/li>\n\n\n\n<li>Test compatibility and file handling on physical devices.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>A production-quality document scanner combines reliable capture, intuitive page management, secure storage, and convenient PDF sharing.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">These techniques provide a foundation for PDF scanner applications, expense trackers, document organizers, educational tools, and business productivity 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:\/\/android-developers.googleblog.com\/2024\/02\/ml-kit-document-scanner-api.html\" target=\"_blank\" rel=\"noopener\">Android Developers: ML Kit Document Scanner<\/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\/basics\/intents\/result\" target=\"_blank\" rel=\"noopener\">Android Activity Result APIs<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/training\/data-storage\/shared\/documents-files\" target=\"_blank\" rel=\"noopener\">Storage Access Framework<\/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\n\n\n<li><a href=\"https:\/\/developer.android.com\/develop\/ui\/compose\" target=\"_blank\" rel=\"noopener\">Jetpack Compose<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/developer.android.com\/topic\/architecture\" target=\"_blank\" rel=\"noopener\">Android Architecture Guide<\/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>Learn to build a modern Android document scanner using Google ML Kit Document Scanner, Kotlin, and Jetpack Compose. Capture documents with automatic edge detection, crop and enhance pages, support multi-page scanning, generate PDF files, and share scanned documents. Includes Activity Result integration, MVVM architecture, Google Play services requirements, secure file handling, Material 3 UI, testing, and production best practices.<\/p>\n","protected":false},"author":1,"featured_media":353,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":0,"footnotes":""},"categories":[16,3,333,6,5],"tags":[246,248,245,249,28,26,247,250,251],"class_list":["post-352","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-camera-scanner","tag-android-pdf-scanner","tag-gmsdocumentscanner","tag-google-document-scanner","tag-jetpack-compose","tag-kotlin","tag-ml-kit-document-scanner","tag-multi-page-scanner","tag-pdf-generation"],"_links":{"self":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/352","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=352"}],"version-history":[{"count":1,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/352\/revisions"}],"predecessor-version":[{"id":354,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/posts\/352\/revisions\/354"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media\/353"}],"wp:attachment":[{"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/media?parent=352"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/categories?post=352"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moiks.com\/blog\/wp-json\/wp\/v2\/tags?post=352"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}