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