Android ML Kit Document Scanner with Kotlin & Jetpack Compose: Build a PDF Scanning App

Document scanning is one of the most useful features in modern Android productivity applications.

Users frequently need to digitize receipts, invoices, handwritten notes, certificates, business documents, and printed forms.

A traditional document scanner application requires several complex components, including camera integration, document boundary detection, perspective correction, image enhancement, page management, and PDF generation.

Fortunately, Google ML Kit Document Scanner provides a ready-made document scanning experience that handles much of this complexity.

The API offers a Google-provided scanning interface with automatic document detection, cropping, image enhancements, multi-page scanning, and PDF/JPEG output.

In this tutorial, we’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.

We’ll also discuss MVVM architecture, secure storage, Google Play services requirements, error handling, testing, and production best practices.


1. What Is Google ML Kit Document Scanner?

ML Kit Document Scanner is an Android API that provides a complete document scanning workflow.

Instead of building a custom camera scanner, developers launch a Google-provided scanning interface.

The scanner can capture physical documents and return processed image and PDF files to the application.

Key features

  • Automatic document detection.
  • Document edge and corner detection.
  • Perspective correction.
  • Automatic cropping.
  • Image enhancement and filters.
  • Multi-page document scanning.
  • Optional gallery import.
  • JPEG output.
  • PDF output.
  • Google-provided scanner interface.
  • On-device scanning and processing.

The scanner UI is provided by Google Play services rather than implemented manually with Jetpack Compose.

2. Why Use ML Kit Document Scanner?

Building a document scanner from scratch is challenging.

A custom solution typically requires:

  • CameraX integration.
  • Camera lifecycle management.
  • Image capture.
  • Edge detection algorithms.
  • Perspective transformation.
  • Image processing.
  • Document cropping.
  • PDF creation.
  • Device-specific camera handling.

ML Kit Document Scanner handles the capture and processing workflow.

Advantages

Faster development: Integrate a scanner without implementing camera algorithms.

Consistent user experience: Use a standardized scanner interface.

Reduced permissions: No camera permission is required by the host application for the ML Kit scanning workflow.

Multi-page support: Capture several pages in one scanning session.

PDF generation: Receive a PDF directly from the scanner.

Smaller integration footprint: The SDK adds approximately 300 KB to the application download, while its implementation is delivered through Google Play services.

3. Real-World Applications

ApplicationScanner use case
PDF ScannerScan documents into PDF
Expense TrackerCapture receipts
Notes ApplicationScan handwritten notes
Document OrganizerDigitize certificates
Business ApplicationCapture invoices
Educational ApplicationScan study materials
Inventory ApplicationCapture paper records
Productivity UtilitySave and share documents

A document scanner can also be integrated as a feature inside an existing application.

4. How ML Kit Document Scanner Works

The complete workflow:

User Taps Scan Document
          |
          v
Jetpack Compose Screen
          |
          v
ML Kit Document Scanner
          |
          v
Google-Provided Camera UI
          |
          v
Document Detection
          |
          v
Crop and Enhance
          |
          v
Multi-Page Preview
          |
          v
User Confirms Scan
          |
          v
Activity Result
          |
          +-- JPEG Page URIs
          |
          +-- PDF URI
          |
          v
Android Application
          |
          v
Preview / Save / Share

Important architectural detail

The scanner UI is external to your Compose layout.

Your application controls when scanning starts and what happens after the result is returned.

5. Project Requirements

Recommended configuration:

  • Android Studio.
  • Kotlin.
  • Jetpack Compose.
  • Material 3.
  • MVVM architecture.
  • Activity Result APIs.
  • Google Play services.
  • Minimum Android API 21.
  • Device RAM of at least 1.7 GB.

Google documents the Android API 21 and 1.7 GB RAM requirements.

Devices below the supported memory requirement can return an UNSUPPORTED ML Kit error.

6. Create the Android Project

Create an Empty Activity project.

Example:

Project Name: DocumentScanner

Package Name: com.moiks.documentscanner

Language: Kotlin

UI: Jetpack Compose

Minimum SDK: 23

Architecture: MVVM

Although the scanner supports API 21, using API 23 as the minimum for a new application is a reasonable project choice.

7. Add the ML Kit Document Scanner Dependency

Open app/build.gradle.kts.

dependencies {

    implementation(
        "com.google.android.gms:" +
            "play-services-mlkit-document-scanner:16.0.0"
    )

    implementation(
        "androidx.activity:activity-compose:<stable-version>"
    )

    implementation(
        "androidx.lifecycle:lifecycle-viewmodel-compose:<stable-version>"
    )

    implementation(
        "androidx.lifecycle:lifecycle-runtime-compose:<stable-version>"
    )
}

Replace the AndroidX placeholders with compatible stable versions.

Ensure the project includes Google’s Maven repository.

repositories {
    google()
    mavenCentral()
}

Important

The document scanner SDK is distributed through Google Play services.

It is not the same as the bundled ML Kit text-recognition library.

8. Understand Scanner Modes

ML Kit provides three scanner modes.

Scanner modeFunctionality
SCANNER_MODE_BASEBasic document scanning
SCANNER_MODE_BASE_WITH_FILTERBasic scanning with image filters
SCANNER_MODE_FULLFull scanner features, including additional image cleanup capabilities

Recommendation

Use SCANNER_MODE_FULL for a document scanner application when you want the richest supported editing experience.

The exact available UI features can depend on the Google Play services implementation.

9. Configure Scanner Options

Create a scanner configuration.

val options =
    GmsDocumentScannerOptions.Builder()
        .setGalleryImportAllowed(true)
        .setPageLimit(20)
        .setResultFormats(
            GmsDocumentScannerOptions.RESULT_FORMAT_JPEG,
            GmsDocumentScannerOptions.RESULT_FORMAT_PDF
        )
        .setScannerMode(
            GmsDocumentScannerOptions.SCANNER_MODE_FULL
        )
        .build()

Explanation

setGalleryImportAllowed(true) enables importing images from the gallery.

setPageLimit(20) limits the number of pages in a scanning session.

setResultFormats() requests JPEG page images and a PDF document.

setScannerMode() selects the scanning feature set.

Recommendation

For an initial version, support 10–20 pages per session.

Test memory usage and file sizes before increasing the limit.

10. Initialize the Document Scanner

Create a scanner client.

val scanner =
    GmsDocumentScanning.getClient(options)

Required imports:

import com.google.mlkit.vision.documentscanner.GmsDocumentScanning
import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions

The scanner provides an intent sender that launches the document scanning workflow.

11. Understand Activity Result Integration

Modern Android applications should use the Activity Result API rather than the deprecated startActivityForResult() pattern.

For document scanning, use:

ActivityResultContracts.StartIntentSenderForResult()

The scanner returns its result after the user completes or cancels the scanning process.

Result states

  • Successful scan.
  • User cancellation.
  • Scanner failure.

Handle these states separately.

12. Launch the Scanner from Jetpack Compose

The following example demonstrates the core integration.

@Composable
fun DocumentScannerLauncher(
    onScanCompleted: (Uri?, List<Uri>) -> Unit,
    onError: (String) -> Unit
) {
    val context = LocalContext.current

    val activity = context as? Activity

    val options = remember {
        GmsDocumentScannerOptions.Builder()
            .setGalleryImportAllowed(true)
            .setPageLimit(20)
            .setResultFormats(
                GmsDocumentScannerOptions.RESULT_FORMAT_JPEG,
                GmsDocumentScannerOptions.RESULT_FORMAT_PDF
            )
            .setScannerMode(
                GmsDocumentScannerOptions.SCANNER_MODE_FULL
            )
            .build()
    }

    val scanner = remember(options) {
        GmsDocumentScanning.getClient(options)
    }

    val launcher =
        rememberLauncherForActivityResult(
            contract =
                ActivityResultContracts
                    .StartIntentSenderForResult()
        ) { activityResult ->

            if (activityResult.resultCode == Activity.RESULT_OK) {

                val result =
                    GmsDocumentScanningResult
                        .fromActivityResultIntent(
                            activityResult.data
                        )

                if (result == null) {
                    onError("No scan result received")
                    return@rememberLauncherForActivityResult
                }

                val pdfUri =
                    result.pdf?.uri

                val imageUris =
                    result.pages
                        ?.map { it.imageUri }
                        .orEmpty()

                onScanCompleted(
                    pdfUri,
                    imageUris
                )
            }
        }

    Button(
        onClick = {

            if (activity == null) {
                onError("Activity unavailable")
                return@Button
            }

            scanner.getStartScanIntent(activity)
                .addOnSuccessListener { intentSender ->

                    val request =
                        IntentSenderRequest.Builder(
                            intentSender
                        ).build()

                    launcher.launch(request)
                }
                .addOnFailureListener { error ->

                    onError(
                        error.message
                            ?: "Unable to start scanner"
                    )
                }
        }
    ) {
        Text("Scan Document")
    }
}

Important considerations

A production implementation should also handle:

  • User cancellation.
  • Scanner availability.
  • Loading states.
  • Rapid repeated taps.
  • Exceptions when launching the intent sender.
  • Activity lifecycle changes.

13. Understand the Scan Result

ML Kit returns a GmsDocumentScanningResult.

The result may contain:

  • Scanned JPEG pages.
  • A generated PDF.
  • PDF page count.

The available outputs depend on the configured result formats.

Example

val result =
    GmsDocumentScanningResult
        .fromActivityResultIntent(data)

val pages = result?.pages

val pdf = result?.pdf

Do not assume both formats are always available.

14. Get Scanned JPEG Pages

Each scanned page contains an image URI.

val imageUris =
    result?.pages
        ?.map { page ->
            page.imageUri
        }
        .orEmpty()

These URIs can be used to display document thumbnails or previews.

Recommended behavior

Do not load all full-resolution images into memory simultaneously.

Use efficient image loading and thumbnail decoding.

15. Get the Generated PDF

If PDF output was requested:

val pdf = result?.pdf

val pdfUri = pdf?.uri

val pageCount = pdf?.pageCount ?: 0

Important distinction

ML Kit already generates the PDF.

You do not need to manually convert every scanned image into a PDF unless your application requires custom layouts or additional processing.

16. Create a Scanned Document Model

Keep scanner-specific APIs separate from your application state.

data class ScannedDocument(
    val id: String,
    val pdfUri: Uri?,
    val pageUris: List<Uri>,
    val pageCount: Int,
    val createdAt: Long
)

Benefits

  • Easier ViewModel management.
  • Simpler UI rendering.
  • Better testability.
  • Support for document history.
  • Future Room integration.

Important consideration

Scanner output URIs should not automatically be treated as permanent storage.

Copy files into an appropriate application-owned location when long-term retention is required.

17. Create Document Scanner UI State

data class DocumentScannerUiState(
    val isLaunchingScanner: Boolean = false,
    val isSaving: Boolean = false,
    val document: ScannedDocument? = null,
    val errorMessage: String? = null
)

This state model separates scanning, saving, results, and errors.

18. Create the Scanner ViewModel

class DocumentScannerViewModel : ViewModel() {

    private val _uiState =
        MutableStateFlow(
            DocumentScannerUiState()
        )

    val uiState = _uiState.asStateFlow()

    fun setLaunching(launching: Boolean) {

        _uiState.update {
            it.copy(
                isLaunchingScanner = launching
            )
        }
    }

    fun onScanCompleted(
        pdfUri: Uri?,
        imageUris: List<Uri>,
        pageCount: Int
    ) {

        val document =
            ScannedDocument(
                id = UUID.randomUUID().toString(),
                pdfUri = pdfUri,
                pageUris = imageUris,
                pageCount = pageCount,
                createdAt =
                    System.currentTimeMillis()
            )

        _uiState.update {
            it.copy(
                isLaunchingScanner = false,
                document = document,
                errorMessage = null
            )
        }
    }

    fun onScanError(message: String) {

        _uiState.update {
            it.copy(
                isLaunchingScanner = false,
                errorMessage = message
            )
        }
    }

    fun clearError() {

        _uiState.update {
            it.copy(errorMessage = null)
        }
    }
}

Architecture recommendation

Keep the Activity Result launcher in the Activity or Compose UI layer.

The ViewModel should receive scan results rather than directly own Android activity-launching APIs.

19. Build a Premium Document Scanner Screen

Suggested UI layout:

+--------------------------------+
|         Document Scanner       |
|                                |
|     Scan Documents to PDF      |
|                                |
|       [ Scan Document ]        |
|                                |
|--------------------------------|
|                                |
|       Recently Scanned         |
|                                |
|  +----------+  +----------+    |
|  | Page 1   |  | Page 2   |    |
|  | Preview  |  | Preview  |    |
|  +----------+  +----------+    |
|                                |
|  Document_2026.pdf             |
|  2 Pages                       |
|                                |
|  [Save PDF]    [Share]          |
+--------------------------------+

UI recommendations

Use Material 3.

Provide a prominent Scan Document button.

Display page thumbnails.

Show the PDF page count.

Offer Save and Share actions.

Support dark and light themes.

20. Create a Document Preview Card

@Composable
fun ScannedDocumentCard(
    document: ScannedDocument
) {
    ElevatedCard(
        modifier = Modifier.fillMaxWidth()
    ) {

        Column(
            modifier = Modifier.padding(16.dp),
            verticalArrangement =
                Arrangement.spacedBy(8.dp)
        ) {

            Text(
                text = "Scanned Document",
                style =
                    MaterialTheme.typography.titleLarge
            )

            Text(
                text = "${document.pageCount} pages"
            )

            Text(
                text = "PDF available: " +
                    (document.pdfUri != null)
            )
        }
    }
}

For a production application, add:

  • Document thumbnail.
  • File name.
  • File size.
  • Scan date.
  • Rename action.
  • Save button.
  • Share button.

21. Display Scanned Page Thumbnails

You can use an image-loading library such as Coil to display JPEG URIs.

Example:

@Composable
fun ScannedPageThumbnail(
    imageUri: Uri
) {
    AsyncImage(
        model = imageUri,
        contentDescription = "Scanned page",
        modifier = Modifier
            .fillMaxWidth()
            .height(240.dp),
        contentScale = ContentScale.Fit
    )
}

Important

Add the compatible Coil Compose dependency.

Use thumbnail sizing and caching to avoid decoding full-resolution pages unnecessarily.

22. Display Multiple Scanned Pages

Use a LazyRow or LazyVerticalGrid.

@Composable
fun ScannedPagesRow(
    imageUris: List<Uri>
) {
    LazyRow(
        horizontalArrangement =
            Arrangement.spacedBy(12.dp),
        contentPadding =
            PaddingValues(16.dp)
    ) {

        items(imageUris) { uri ->

            Box(
                modifier = Modifier.width(160.dp)
            ) {
                ScannedPageThumbnail(uri)
            }
        }
    }
}

Recommendation

For large documents, show a grid with page numbers.

Allow users to tap a page for full-screen preview.

23. Save the PDF Using Storage Access Framework

The Storage Access Framework allows users to choose where to save their scanned PDF.

Use:

ActivityResultContracts.CreateDocument(
    "application/pdf"
)

This approach avoids requesting broad storage permissions.

Compose example

@Composable
fun SavePdfButton(
    sourcePdfUri: Uri
) {
    val context = LocalContext.current

    val launcher =
        rememberLauncherForActivityResult(
            contract =
                ActivityResultContracts.CreateDocument(
                    "application/pdf"
                )
        ) { destinationUri ->

            if (destinationUri != null) {

                runCatching {

                    context.contentResolver
                        .openInputStream(sourcePdfUri)
                        ?.use { input ->

                            context.contentResolver
                                .openOutputStream(destinationUri)
                                ?.use { output ->

                                    input.copyTo(output)
                                }
                        }
                }
            }
        }

    Button(
        onClick = {
            launcher.launch(
                "Scanned_Document.pdf"
            )
        }
    ) {
        Text("Save PDF")
    }
}

Production improvement

Perform file copying on Dispatchers.IO.

Check that both streams open successfully.

Report copy failures to the user.

Avoid performing large file operations on the main thread.

24. Save Scans to App-Specific Storage

Another option is to save the PDF in your application’s private files directory.

suspend fun savePdfToAppStorage(
    context: Context,
    sourceUri: Uri,
    fileName: String
): File = withContext(Dispatchers.IO) {

    val directory =
        File(
            context.filesDir,
            "scanned_documents"
        ).apply {
            mkdirs()
        }

    val destination =
        File(directory, fileName)

    context.contentResolver
        .openInputStream(sourceUri)
        ?.use { input ->

            destination.outputStream().use { output ->
                input.copyTo(output)
            }
        }
        ?: throw IOException(
            "Unable to open source PDF"
        )

    destination
}

Important security consideration

Validate generated file names.

Avoid using untrusted paths directly.

App-specific storage is appropriate for private document history.

25. Share Scanned PDFs

To share a PDF URI:

fun sharePdf(
    context: Context,
    pdfUri: Uri
) {
    val intent =
        Intent(Intent.ACTION_SEND).apply {

            type = "application/pdf"

            putExtra(
                Intent.EXTRA_STREAM,
                pdfUri
            )

            addFlags(
                Intent.FLAG_GRANT_READ_URI_PERMISSION
            )
        }

    context.startActivity(
        Intent.createChooser(
            intent,
            "Share scanned PDF"
        )
    )
}

Important

The URI must be accessible to the receiving application.

For PDFs saved as private files, expose them through a correctly configured FileProvider rather than using file:// URIs.

26. Handle Scanner Cancellation

Users may close the scanner without completing a scan.

This is normal behavior.

when (activityResult.resultCode) {

    Activity.RESULT_OK -> {
        // Process scan.
    }

    Activity.RESULT_CANCELED -> {
        // User canceled.
    }

    else -> {
        // Handle unexpected result.
    }
}

UX recommendation

Do not display an error dialog when the user intentionally cancels.

Return to the previous screen gracefully.

27. Handle Unsupported Devices

ML Kit Document Scanner requires a supported Google Play services environment.

It also requires at least 1.7 GB of total device RAM.

On unsupported devices, the API may return an MlKitException with an UNSUPPORTED error code.

Recommended behavior

Display:

“Document scanning is not supported on this device.”

Offer another import method when appropriate.

Do not assume every Android device supports the Google-provided scanner.

28. Understand Google Play Services Requirements

The document scanner implementation is delivered dynamically through Google Play services.

What this means

  • Initial scanning may require downloading components.
  • The first launch may take longer.
  • Network connectivity may be needed for initial setup.
  • The scanner is not guaranteed to work on devices without the required Google Play services support.

Important distinction

The scanner processes documents on-device, but its components may require an initial download.

Do not advertise guaranteed first-launch offline scanning.

29. Add Gallery Import

Enable gallery import using:

.setGalleryImportAllowed(true)

This allows users to import existing images through the scanner interface.

Recommended use cases

  • Previously captured receipts.
  • Screenshots of documents.
  • Saved forms.
  • Existing document photographs.

Privacy advantage

The scanner can handle gallery selection without requiring broad media-library access from the host application.

30. Understand Automatic Document Detection

The scanner can detect document edges and corners.

This improves scanning quality when users photograph documents at an angle.

Typical workflow

Camera Preview
      |
      v
Document Boundary Detection
      |
      v
Perspective Correction
      |
      v
Cropped Document

Important limitation

Detection quality depends on lighting, contrast, document condition, and camera quality.

Users should still be able to review the scanned result.

31. Understand Image Enhancement

The scanner supports image enhancement and filters according to the selected scanner mode.

Potential improvements include:

  • Contrast enhancement.
  • Color adjustments.
  • Document cleanup.
  • Perspective correction.
  • Stain or blemish reduction.

Recommendation

Use the full scanner mode when you want the richest available editing experience.

Let users review the processed document before saving.

32. Multi-Page PDF Scanning

A useful scanner should support several pages in one document.

Example:

Page 1: Invoice

Page 2: Invoice Details

Page 3: Payment Information

The scanner can return one PDF containing all pages.

Implementation

Configure:

.setPageLimit(20)

And request:

.setResultFormats(
    GmsDocumentScannerOptions.RESULT_FORMAT_PDF
)

Recommendation

Use the returned PDF directly rather than reconstructing it unnecessarily from JPEG pages.

33. Add Document Renaming

Users should be able to choose descriptive document names.

Examples:

Electricity_Bill_October.pdf

Office_Invoice_2026.pdf

Project_Notes.pdf

Travel_Receipts.pdf

Recommended behavior

Provide a default name.

Allow editing before saving.

Sanitize file names.

Avoid duplicate-name conflicts.

34. Add Recent Document History

A production scanner can maintain a history of saved documents.

Suggested model:

data class DocumentHistoryItem(
    val id: String,
    val title: String,
    val localPath: String,
    val pageCount: Int,
    val createdAt: Long
)

Use Room to store document metadata.

Recommended features

  • Recent scans.
  • Search documents.
  • Rename documents.
  • Delete documents.
  • Share documents.
  • Sort by date.
  • Sort by name.

Important

Store durable document paths or identifiers, not temporary scanner URIs that may expire.

35. Add PDF Preview

Android provides PdfRenderer for rendering PDF pages.

A PDF preview screen can display:

  • Individual pages.
  • Page numbers.
  • Zoom controls.
  • Scrollable previews.
  • Document information.

Important consideration

PdfRenderer requires a seekable file descriptor.

Depending on the URI provider, you may need to copy the PDF into a suitable local file first.

Close the renderer and its underlying file descriptor when finished.

36. Add OCR as an Optional Feature

Document scanning and OCR are different technologies.

Document Scanner: Captures and processes document images.

Text Recognition: Extracts readable text from images.

To build a searchable document scanner, combine ML Kit Document Scanner with ML Kit Text Recognition.

Workflow

Document Scanner
       |
       v
Scanned JPEG Pages
       |
       v
ML Kit Text Recognition
       |
       v
Extracted Text
       |
       v
Searchable Document Metadata

Important distinction

The Document Scanner API does not automatically provide extracted OCR text.

A PDF returned by the scanner should not be assumed to contain a searchable text layer.

37. Recommended MVVM Architecture

Suggested project structure:

com.moiks.documentscanner/
|
+-- data/
|   +-- scanner/
|   |   +-- DocumentRepository.kt
|   |
|   +-- storage/
|   |   +-- PdfStorageManager.kt
|   |   +-- DocumentFileProvider.kt
|   |
|   +-- local/
|       +-- DocumentDao.kt
|       +-- DocumentDatabase.kt
|
+-- domain/
|   +-- model/
|   |   +-- ScannedDocument.kt
|   |   +-- DocumentHistoryItem.kt
|   |
|   +-- usecase/
|       +-- SaveScannedDocumentUseCase.kt
|       +-- DeleteDocumentUseCase.kt
|
+-- presentation/
|   +-- DocumentScannerViewModel.kt
|   +-- DocumentScannerUiState.kt
|
+-- ui/
|   +-- DocumentScannerScreen.kt
|   +-- DocumentPreviewScreen.kt
|   +-- ScannedPageThumbnail.kt
|   +-- DocumentHistoryScreen.kt
|
+-- MainActivity.kt

Responsibilities

Compose UI: Launches scanner and displays results.

ViewModel: Manages document state.

Repository: Coordinates document operations.

Storage Manager: Saves PDF and JPEG files.

Room: Stores persistent metadata.

UseCases: Encapsulate business logic.

38. Performance Optimization

Best practices

  • Avoid decoding full-resolution images unnecessarily.
  • Use thumbnail loading.
  • Perform file operations on background dispatchers.
  • Reuse existing PDFs instead of recreating them.
  • Limit unnecessary memory allocations.
  • Release PDF renderers.
  • Avoid retaining large Bitmaps in ViewModels.
  • Use LazyColumn or LazyVerticalGrid for document history.
  • Test multi-page scanning on lower-memory devices.

Important consideration

Large scanned documents may produce substantial PDF and JPEG files.

Measure file sizes and storage consumption on real devices.

39. Privacy and Security

Scanned documents may contain sensitive information.

Examples include:

  • Identity documents.
  • Financial statements.
  • Medical documents.
  • Contracts.
  • Certificates.
  • Personal addresses.
  • Business invoices.

Recommended practices

Store documents privately by default.

Avoid uploading files without user consent.

Do not log document contents.

Use FileProvider for controlled sharing.

Grant temporary URI access.

Avoid broad storage permissions.

Provide document deletion controls.

Explain how scanned files are stored and shared.

Important distinction

On-device scanning does not automatically secure files after they are saved or shared.

40. Testing Strategy

Test scenarioExpected behavior
Single-page documentSuccessful scan
Multi-page documentCorrect page count
PDF outputValid PDF URI
JPEG outputValid page URIs
Gallery importImage selection works
Scanner cancellationGraceful return
Low-light documentUser can review result
Angled documentCrop and correction
Model download requiredLoading handled
No network on first launchHelpful failure handling
Offline after setupSupported workflow tested
Unsupported deviceClear error
Save PDFFile written correctly
Share PDFReceiver can open file
Large PDFNo UI freezing
Device rotationState handled
Dark themeReadable UI
TabletResponsive layout

Additional tests

Verify that exported PDFs open in multiple PDF viewers.

Check that files remain accessible after app restart.

Test repeated scans.

Test storage-full conditions.

Test interrupted file copying.

41. Common Document Scanner Mistakes

Mistake 1: Requesting Camera Permission Unnecessarily

The ML Kit scanner workflow does not require your application to request camera permission.

Mistake 2: Assuming All Devices Are Supported

Google Play services and hardware requirements apply.

Mistake 3: Assuming the Scanner Works Offline on First Launch

Initial components may require downloading.

Mistake 4: Recreating the PDF Unnecessarily

The scanner can return a ready-made PDF.

Mistake 5: Keeping Only Temporary URIs

Copy important documents into durable storage.

Mistake 6: Blocking the Main Thread During File Copying

Use Dispatchers.IO.

Mistake 7: Loading Full-Resolution Pages into Memory

Use efficient thumbnail loading.

Mistake 8: Sharing Private File Paths Directly

Use content URIs and appropriate grants.

Mistake 9: Assuming the PDF Contains OCR Text

Document scanning and text recognition are separate operations.

Mistake 10: Ignoring Cancellation

User cancellation is not an application error.

42. Production Checklist

Before publishing:

  • ML Kit Document Scanner dependency is configured.
  • Minimum SDK is supported.
  • Google Play services requirements are understood.
  • Unsupported devices are handled.
  • Scanner modes are configured.
  • Gallery import is configured.
  • Page limits are configured.
  • PDF output is enabled.
  • JPEG output is enabled if needed.
  • Activity Result integration works.
  • Cancellation is handled.
  • Scanner errors are handled.
  • PDF files are saved safely.
  • Temporary URIs are not used as permanent references.
  • Sharing uses content URI permissions.
  • PDF previews work.
  • Document history works if implemented.
  • Storage-full conditions are handled.
  • Privacy protections are implemented.
  • 16 KB page-size compatibility is verified.
  • Physical Android devices are tested.

43. Frequently Asked Questions

What is ML Kit Document Scanner?

It is Google’s Android document scanning API that provides document capture, cropping, enhancement, and PDF/JPEG output.

Does it require camera permission?

No. The Google-provided scanning workflow does not require camera permission from the host application.

Does it support PDF generation?

Yes. It can return a PDF containing scanned pages.

Does it support multiple pages?

Yes. Developers can configure the maximum number of pages.

Does it support gallery import?

Yes. Gallery import can be enabled through scanner options.

Does it automatically crop documents?

Yes. The scanning experience includes document detection and cropping capabilities.

Does it support image filters?

Yes. Available enhancement capabilities depend on the scanner mode.

Does it work offline?

Scanning can work after the required components are available, but the initial Google Play services download may require connectivity.

Does it require a backend?

No backend is required for basic document scanning.

Can I use it with Jetpack Compose?

Yes. Launch the scanner using the Activity Result API from a Compose application.

Does it support Android 5.0?

The documented minimum is Android API 21, subject to Google Play services and device requirements.

Can I build a PDF scanner application with it?

Yes. The API provides the core scanning workflow needed for a PDF scanner.

Does it extract text automatically?

No. Use a separate OCR API such as ML Kit Text Recognition for extracted text.

Can I store scanned PDFs locally?

Yes. Use app-specific storage or the Storage Access Framework.

Is it suitable for production apps?

Yes, provided you handle supported devices, scanner availability, file storage, sharing, privacy, and release compatibility.

Conclusion

Google ML Kit Document Scanner significantly simplifies document scanning development on Android.

Instead of implementing a custom camera pipeline, document boundary detection, perspective correction, image enhancement, and PDF generation, developers can integrate Google’s scanning workflow.

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.

The most important practices are:

  • Use the official ML Kit Document Scanner dependency.
  • Configure scanner modes and output formats.
  • Launch scanning through Activity Result APIs.
  • Handle cancellation and unsupported devices.
  • Retrieve JPEG pages and PDF output.
  • Save documents into durable storage.
  • Share files using content URIs.
  • Perform file operations off the main thread.
  • Use efficient image previews.
  • Protect sensitive scanned documents.
  • Add OCR separately when searchable text is required.
  • Test compatibility and file handling on physical devices.

A production-quality document scanner combines reliable capture, intuitive page management, secure storage, and convenient PDF sharing.

These techniques provide a foundation for PDF scanner applications, expense trackers, document organizers, educational tools, and business productivity utilities.

Official References


Published by Moiks Developer Blog — Practical tutorials covering Android, Kotlin, Jetpack Compose, Flutter, React Native, SwiftUI, and modern software engineering.

Explore Apps by Moiks Studio

Discover our Android apps and games on Google Play.

View All Android Apps →

Leave a Comment