跳到正文
DEV Community· ClearDesk Tools·· 1 小時前AI 評分46

如何用 ML Kit 和 Jetpack Compose 為 Android 建立離線文件掃描器

Building an offline document scanner for Android with ML Kit and Jetpack Compose

AI 導讀

Paperly 使用 ML Kit 和 Jetpack Compose 建立 Android 離線文件掃描器,掃描、OCR、PDF 工具及簽署均在裝置上執行,無需後端、帳戶或付費 API。文章説明如何預先載入掃描模組、以多種文字辨識器自動處理不同文字系統,以及用 PdfBox 生成 PDF、設定 AES-256 密碼保護和避免匯出檔案被覆寫。完整專案有 91 個 Kotlin 檔案,售價 $49。

正文

A year ago "scan a document on Android" meant OpenCV and a week of edge-detection tuning. Today ML Kit's document scanner gives you the camera UI, edge detection, crop, perspective fix and filters in one intent. But wiring it into a real, fully-offline app still has sharp edges. This is how Paperly works: a scanner app where scanning, OCR, PDF tools and signing all run on-device. No backend, no account, no paid APIs.

The stack: Kotlin 2.0, Jetpack Compose (BOM 2025.06), ML Kit document scanner + text recognition + barcode scanning, CameraX, PdfBox for PDFs. minSdk 26, targetSdk 36. Room for the library, 15 languages, unit tests over the OCR and PDF logic.

1. The scanner's first-run trap

ML Kit's document scanner is delivered through Play services, and its UI and ML models (edge detection, filters, the "Clean" mode) download on first use. On a fresh install, a user on a slow connection could open the scanner before the module landed, and FULL-mode features would silently not work.

The fix is to warm the module during onboarding, before the first scan:

suspend fun warmScanner(context: Context) {
    try {
        val scanner = GmsDocumentScanning.getClient(
            GmsDocumentScannerOptions.Builder()
                .setScannerMode(GmsDocumentScannerOptions.SCANNER_MODE_FULL)
                .setGalleryImportAllowed(true)
                .setPageLimit(1000)
                .setResultFormats(GmsDocumentScannerOptions.RESULT_FORMAT_JPEG)
                .build()
        )
        val request = ModuleInstallRequest.newBuilder().addApi(scanner).build()
        ModuleInstall.getClient(context.applicationContext)
            .installModules(request).await()
    } catch (e: Exception) {
        if (e is CancellationException) throw e
    }
}

Best-effort by design: if the download fails, scanning still works, just without the extras until Play services finishes in the background.

2. Multi-script OCR without asking the user which script it is

ML Kit ships separate recognizers for Latin, Devanagari, Chinese, Japanese and Korean. Paperly lets the user pick a script, but the default is Auto: decode the photo once at a bounded size (2600 px keeps large photos from blowing up memory on low-RAM phones), then run the recognizers in likelihood order and keep the fullest result:

val order = listOf("Latin", "Devanagari", "Japanese", "Korean", "Chinese")
var best = "" to "Latin"
for (script in order) {
    currentCoroutineContext().ensureActive()
    val text = try {
        recognizer(script).process(InputImage.fromBitmap(image, 0)).await().text
    } catch (e: Exception) {
        if (e is CancellationException) throw e; ""
    }
    if (text.trim().length > best.first.trim().length) best = text to script
    // stop early on a confident read
}

Bounding the decode matters more than it looks: a 50 MP camera photo decoded at full size is a 200 MB bitmap. One bounded decode, reused across every recognizer, keeps OCR responsive on budget phones.

Recognizers are created lazily and cached in a map, so switching scripts doesn't re-download models.

This auto-detect OCR piece is also published on its own as a drop-in Kotlin file, MIT licensed: mlkit-multiscript-ocr on GitHub.

3. Real PDFs with PdfBox: quality presets, AES-256, honest filenames

For PDF generation Paperly uses PdfBox (the Android port). Three details worth stealing:

Quality presets are JPEG quality + max dimension pairs, exposed in words ("Regular", "High") instead of numbers:

enum class Quality(val jpeg: Int, val maxDim: Int, val label: String) {
    LOW(60, 1200, "Low"), REGULAR(70, 1600, "Regular"),
    MEDIUM(78, 2000, "Medium"), HIGH(85, 2600, "High"), MAX(92, 3400, "Max")
}

Password protection is AES-256, and the 127-UTF-8-byte limit is enforced up front so it fails before writing a file, not after:

require(password.toByteArray(Charsets.UTF_8).size <= 127)
val policy = StandardProtectionPolicy(password, password, AccessPermission())
policy.encryptionKeyLength = 256
policy.isPreferAES = true
document.protect(policy)

Every export gets its own directory. A receiving app may read a shared PDF URI after your next export has started. If you overwrite the same file, the receiving app sees a half-written or wrong document. Each export writes to a fresh UUID-named directory, so every published snapshot stays valid:

val dir = File(ExportStore.documentDirectory(context, documentId),
    UUID.randomUUID().toString()).apply { check(mkdirs()) }
return File(dir, "$safe.pdf")

Merge, split and page compression are PDFMergerUtility plus re-encoding at the chosen preset. Drawn signatures are captured on a Compose canvas and stamped as images with PDPageContentStream.

What the full project adds

Everything above is the interesting 10%. The full source adds the parts that take the time: the Room-backed library with tags and search, ID-card and QR modes, an OCR editing queue with per-page re-runs, export to TXT/DOCX/XLSX, 15 locale packs, settings, themes, and the reskin surface (package name, app name, colors, icon, strings - covered in the included reskin guide).

If you're building a scanner or document app and want the head start, the complete project (91 Kotlin files, builds clean on a fresh clone, README + reskin guide included) is $49:

Questions welcome in the comments - happy to go deeper on any of the three sections.

來源:DEV Community · dev.to