Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.
Rust androiddocument-scannerdocximage-editorjetpack-composekotlinliquid-glassofflineopen-sourcepdfpdf-compressorpdf-editorpdf-mergerpdf-readerpdf-splitterpdf-toolspdf-viewerpptxspreadsheet-editorxlsx
ocr mlkit tesseract4android
Chethan616c83f5d0d09cb
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex d9d3e9c..f01c391 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -22,6 +22,20 @@ ClearPDF uses open-source components and keeps their notices with the project. R- License: Apache License 2.0 (as attributed in the Settings screen)- Use: the app's translucent glass surfaces, backdrop effects, and shared UI components.+## Google ML Kit Text Recognition++- Artifact: `com.google.mlkit:text-recognition:16.0.1`+- License: Google APIs Terms of Service (proprietary; the client library, not the on-device model, carries Apache-2.0-style redistribution terms — see Google's ML Kit terms)+- Use: primary on-device OCR engine for scanned/image-only PDF pages (`ocr-core` module). This is the **bundled** artifact — the recognition model ships inside the APK, not the Play-Services-downloaded variant — so it runs fully offline with no network call and no Play Services requirement.+- Notice practice: comply with Google's ML Kit Terms of Service for redistribution; do not imply Google endorses ClearPDF.++## Tesseract4Android / Tesseract OCR / Leptonica++- Artifact: `cz.adaptech.tesseract4android:tesseract4android:4.9.0` (Copyright 2019 Adaptech s.r.o., Robert Pösel)+- License: Apache License 2.0 (wraps the Tesseract OCR engine, also Apache-2.0, and the Leptonica imaging library, BSD-2-Clause)+- Use: fully open-source, offline OCR fallback (`ocr-core` module) used when the bundled ML Kit engine fails to initialize or recognize on a given device. Bundles `eng.traineddata` (English) as a module asset so the fallback needs no download.+- Notice practice: keep the Apache 2.0 license text and the BSD-2-Clause Leptonica notice available with redistributed builds.+## Feature-set inspiration — Pdf_Tools- Project: `Karna14314/Pdf_Tools` (https://github.com/Karna14314/Pdf_Tools)diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 1013ce3..9a1f99c 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -76,6 +76,20 @@ android {buildFeatures {compose = true}+ // Bundling on-device OCR (bundled ML Kit + Tesseract4Android) added native .so libs for+ // 4 CPU architectures; without splitting, every install carries all 4. This produces one+ // APK per ABI (~1/4 the native-lib weight each) plus a universal fallback for sideloading.+ // Play Store distribution via an Android App Bundle (`./gradlew bundleRelease`) already does+ // this automatically and needs no config here — this `splits` block only matters for raw+ // APK builds/installs (`assembleDebug`/`assembleRelease`, `installDebug`, sideloading).+ splits {+ abi {+ isEnable = true+ reset()+ include("armeabi-v7a", "arm64-v8a", "x86", "x86_64")+ isUniversalApk = true+ }+ }packaging {resources {excludes += arrayOf(@@ -128,6 +142,7 @@ dependencies {implementation(libs.kotlinx.serialization.json)implementation(project(":backdrop"))implementation(project(":pdf-core"))+ implementation(project(":ocr-core"))// Apache POI provides legacy .doc/.xls/.ppt text extraction. It is Apache-2.0// licensed; see THIRD_PARTY_NOTICES.md for redistribution requirements.implementation("org.apache.poi:poi:3.17")diff --git a/app/src/main/java/com/chethan616/clearpdf/data/repository/PdfServiceLocator.kt b/app/src/main/java/com/chethan616/clearpdf/data/repository/PdfServiceLocator.ktindex 3859eec..373e363 100644--- a/app/src/main/java/com/chethan616/clearpdf/data/repository/PdfServiceLocator.kt+++ b/app/src/main/java/com/chethan616/clearpdf/data/repository/PdfServiceLocator.kt@@ -16,6 +16,8 @@ import com.kyant.pdfcore.viewer.PdfViewerimport com.kyant.pdfcore.viewer.PdfViewerImplimport com.kyant.pdfcore.text.PdfTextServiceimport com.kyant.pdfcore.text.PdfTextServiceImpl+import com.kyant.ocrcore.OcrService+import com.kyant.ocrcore.OcrServiceImplobject PdfServiceLocator {val pdfViewer: PdfViewer by lazy { PdfViewerImpl() }@@ -26,4 +28,6 @@ object PdfServiceLocator {val pdfEditor: PdfEditor by lazy { PdfEditorImpl() }val pdfConverter: PdfConverter by lazy { PdfConverterImpl() }val pdfTextService: PdfTextService by lazy { PdfTextServiceImpl() }+ /** Fully on-device OCR — ML Kit primary, Tesseract4Android fallback. No network access. */+ val ocrService: OcrService by lazy { OcrServiceImpl() }}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.ktindex 3d1a6dc..05f5739 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/navigation/DocsNavGraph.kt@@ -656,7 +656,11 @@ fun DocsNavGraph(factory = object : ViewModelProvider.Factory {@Suppress("UNCHECKED_CAST")override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T =- ExtractTextViewModel(PdfServiceLocator.pdfConverter) as T+ ExtractTextViewModel(+ PdfServiceLocator.pdfConverter,+ PdfServiceLocator.ocrService,+ PdfServiceLocator.pdfViewer+ ) as T})ExtractTextScreen(diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ExtractTextScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ExtractTextScreen.ktindex d3cfa87..4692e45 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ExtractTextScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ExtractTextScreen.kt@@ -163,11 +163,53 @@ fun ExtractTextScreen(}state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFFFB300), 12.sp)) }+ if (state.canRecognize && !state.isRecognizing) {+ LiquidButton(+ onClick = { viewModel.recognizeText(context) },+ backdrop = backdrop,+ tint = accent,+ modifier = Modifier.fillMaxWidth()+ ) {+ BasicText(stringResource(R.string.extract_recognize_text), style = TextStyle(Color.White, 14.sp, FontWeight.Medium))+ }+ }+ if (state.canMakeSearchable) {+ LiquidButton(+ onClick = { viewModel.makeSearchablePdf(context) },+ backdrop = backdrop,+ tint = Color(0xFF2E7D32),+ modifier = Modifier.fillMaxWidth()+ ) {+ if (state.isSavingSearchable) {+ CircularProgressIndicator(color = Color.White, strokeWidth = 2.dp, modifier = Modifier.size(16.dp))+ } else {+ BasicText(stringResource(R.string.extract_make_searchable), style = TextStyle(Color.White, 14.sp, FontWeight.Medium))+ }+ }+ }+ if (state.searchableOutputUri != null) {+ BasicText(+ stringResource(R.string.extract_searchable_saved, state.searchableSavedLabel.orEmpty()),+ style = TextStyle(Color(0xFF2E7D32), 12.sp)+ )+ }+Box(Modifier.fillMaxWidth().weight(1f).liquidGlassPanel(backdrop, uiSensor).padding(14.dp)) {when {state.isExtracting -> Box(Modifier.fillMaxSize(), Alignment.Center) {CircularProgressIndicator(color = accent, strokeWidth = 2.dp)}+ state.isRecognizing -> Box(Modifier.fillMaxSize(), Alignment.Center) {+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(10.dp)) {+ CircularProgressIndicator(color = accent, strokeWidth = 2.dp)+ val progress = state.recognizeProgress+ BasicText(+ if (progress != null) stringResource(R.string.extract_recognizing, progress.first + 1, progress.second)+ else stringResource(R.string.extract_recognize_text),+ style = TextStyle(sub, 12.sp)+ )+ }+ }state.text.isNotEmpty() -> SelectionContainer(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {BasicText(state.text, style = TextStyle(text, 14.sp))}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.ktindex a3900a3..1c5a572 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt@@ -13,7 +13,9 @@ import androidx.compose.foundation.gestures.detectDragGesturesimport androidx.compose.foundation.gestures.detectDragGesturesAfterLongPressimport androidx.compose.foundation.gestures.detectTapGesturesimport androidx.compose.foundation.gestures.waitForUpOrCancellation+import androidx.compose.foundation.horizontalScrollimport androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.aspectRatio@@ -23,9 +25,19 @@ import androidx.compose.foundation.layout.offsetimport androidx.compose.foundation.layout.paddingimport androidx.compose.foundation.layout.sizeimport androidx.compose.foundation.layout.width+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.text.BasicText+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.rounded.ContentCopy+import androidx.compose.material.icons.rounded.Delete+import androidx.compose.material.icons.rounded.FormatUnderlined+import androidx.compose.material.icons.rounded.Highlight+import androidx.compose.material.icons.rounded.SelectAll+import androidx.compose.material.icons.rounded.StrikethroughSimport androidx.compose.material3.CircularProgressIndicator+import androidx.compose.material3.Iconimport androidx.compose.runtime.Composableimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOf@@ -47,6 +59,7 @@ import androidx.compose.ui.graphics.drawscope.Strokeimport androidx.compose.ui.graphics.drawscope.drawIntoCanvasimport androidx.compose.ui.graphics.nativeCanvasimport androidx.compose.ui.graphics.toArgb+import androidx.compose.ui.graphics.vector.ImageVectorimport androidx.compose.ui.geometry.CornerRadiusimport androidx.compose.ui.input.pointer.pointerInputimport androidx.compose.ui.layout.ContentScale@@ -65,6 +78,22 @@ import com.chethan616.clearpdf.ui.viewmodel.OcrTextRangeimport kotlin.math.maximport kotlin.math.min+/** One icon+label action in the stock-style text-selection menu (Acrobat/Drive look). */+@Composable+private fun SelectionMenuItem(icon: ImageVector, label: String, tint: Color, onClick: () -> Unit) {+ Column(+ Modifier+ .clip(RoundedCornerShape(8.dp))+ .clickable(onClick = onClick)+ .padding(horizontal = 10.dp, vertical = 6.dp)+ .width(52.dp),+ horizontalAlignment = Alignment.CenterHorizontally+ ) {+ Icon(icon, label, Modifier.size(20.dp), tint)+ BasicText(label, style = TextStyle(tint, 10.sp, FontWeight.Medium), maxLines = 1)+ }+}+/*** A single page inside the continuous (Adobe-style) vertical viewer.*@@ -109,6 +138,9 @@ internal fun PdfContinuousPage(onDeleteMarkup: (Int) -> Unit = {},onCopySelection: () -> Unit = {},onHighlightSelection: () -> Unit = {},+ onUnderlineSelection: () -> Unit = {},+ onStrikeSelection: () -> Unit = {},+ onSetColorLong: (Long) -> Unit = {},onSelectAll: () -> Unit = {}) {var draftPoints by remember(page, activeTool) { mutableStateOf<List<Offset>>(emptyList()) }@@ -170,10 +202,10 @@ internal fun PdfContinuousPage(selectedOcrRanges.forEach { range ->ocrBlocks.firstOrNull { it.id == range.blockId }?.let { b ->val r = expandedTextHighlightRect(ocrTextRangeToRect(b, range, frame), verticalScale = 1.35f)- // Match the reference's soft cyan fill: no border, no font changes, and- // enough vertical air for ascenders/descenders without covering other lines.+ // Stock-Android text-selection look: a subtle translucent band in the same+ // blue as the selection handles (#4285F4), not an opaque saturated cyan block.val radius = (r.height * 0.14f).coerceIn(2f, 5f)- drawRoundRect(Color(0xFF9ADBF0).copy(0.82f), r.topLeft, r.size, CornerRadius(radius, radius))+ drawRoundRect(Color(0xFF4285F4).copy(0.28f), r.topLeft, r.size, CornerRadius(radius, radius))}}@@ -312,8 +344,16 @@ internal fun PdfContinuousPage(if (activeTool == PdfEditTool.SelectText) {ocrSelectionHandleAnchors(ocrBlocks, selectedOcrRanges, frame)?.let { (start, end) ->- drawTextSelectionHandle(start, selectionHandleDiameterPx)- drawTextSelectionHandle(end, selectionHandleDiameterPx)+ // Size each handle off its own line's rendered height, clamped to a sane+ // touch-target range, instead of a fixed dp that ignores the page's current+ // zoom/fit-width scale (see ocrSelectionHandleLineHeights doc).+ val (startLineH, endLineH) = ocrSelectionHandleLineHeights(ocrBlocks, selectedOcrRanges, frame)+ ?: (selectionHandleDiameterPx to selectionHandleDiameterPx)+ // DrawScope is itself a Density, so dp -> px works directly here.+ val minPx = 14.dp.toPx()+ val maxPx = 30.dp.toPx()+ drawTextSelectionHandle(start, (startLineH * 1.1f).coerceIn(minPx, maxPx))+ drawTextSelectionHandle(end, (endLineH * 1.1f).coerceIn(minPx, maxPx))}}@@ -675,63 +715,74 @@ internal fun PdfContinuousPage(marks.any { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId == id }}val gapPx = with(density) { 8.dp.toPx() }- val bubbleHpx = with(density) { 44.dp.toPx() }- val bubbleWpx = with(density) { (if (selectionHasHighlight) 372.dp else 296.dp).toPx() }+ val bubbleHpx = with(density) { 148.dp.toPx() }+ val itemCount = if (selectionHasHighlight) 6 else 5+ val bubbleWpx = with(density) { (itemCount * 60).dp.toPx() }// Flip below the selection when it's too close to the page top.val placeBelow = selTop < bubbleHpx + gapPxval by = (if (placeBelow) selBottom + gapPx else selTop - bubbleHpx - gapPx).coerceIn(0f, (csz.height - bubbleHpx).coerceAtLeast(0f))val bx = ((selLeft + selRight) / 2f - bubbleWpx / 2f).coerceIn(0f, (csz.width - bubbleWpx).coerceAtLeast(0f))- Row(+ // Icon-menu look (Acrobat/Drive-style), not a pill of coloured text: a plain+ // dark card, one icon+label column per action, neutral colour throughout except+ // the active/applied state and the destructive action.+ val menuFg = Color(0xFFCCCCCC)+ Column(Modifier.offset { IntOffset(bx.roundToInt(), by.roundToInt()) }- .clip(RoundedCornerShape(22.dp))- .background(Color(0xFF1C1F26).copy(0.97f))- .border(1.dp, Color.White.copy(0.14f), RoundedCornerShape(22.dp))- .padding(horizontal = 4.dp, vertical = 3.dp),- verticalAlignment = Alignment.CenterVertically+ .clip(RoundedCornerShape(14.dp))+ .background(Color(0xFF232629))+ .border(1.dp, Color.White.copy(0.08f), RoundedCornerShape(14.dp))) {- BasicText(- "Copy",- style = TextStyle(Color.White, 13.sp, FontWeight.SemiBold),- modifier = Modifier- .clip(RoundedCornerShape(18.dp))- .clickable { onCopySelection(); onClearOcrSelection() }- .padding(horizontal = 16.dp, vertical = 9.dp)- )- Box(Modifier.width(1.dp).height(20.dp).background(Color.White.copy(0.14f)))- BasicText(- "Select all",- style = TextStyle(Color.White, 13.sp, FontWeight.SemiBold),- modifier = Modifier- .clip(RoundedCornerShape(18.dp))- .clickable { onSelectAll() }- .padding(horizontal = 16.dp, vertical = 9.dp)- )- Box(Modifier.width(1.dp).height(20.dp).background(Color.White.copy(0.14f)))- BasicText(- if (selectionHasHighlight) "Recolor" else "Highlight",- style = TextStyle(Color(0xFFFFCC33), 13.sp, FontWeight.SemiBold),- modifier = Modifier- .clip(RoundedCornerShape(18.dp))- .clickable { onHighlightSelection() }- .padding(horizontal = 16.dp, vertical = 9.dp)- )- if (selectionHasHighlight) {- Box(Modifier.width(1.dp).height(20.dp).background(Color.White.copy(0.14f)))- BasicText(- "Delete",- style = TextStyle(Color(0xFFFF6B6B), 13.sp, FontWeight.SemiBold),- modifier = Modifier- .clip(RoundedCornerShape(18.dp))- .clickable {- // Drop every highlight sitting on a selected word, then clear the- // selection so the pill dismisses.- marks.removeAll { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId in selectedOcrIds }- onClearOcrSelection()- }- .padding(horizontal = 16.dp, vertical = 9.dp)- )+ Row(+ Modifier+ .padding(horizontal = 4.dp, vertical = 6.dp)+ .horizontalScroll(rememberScrollState()),+ verticalAlignment = Alignment.CenterVertically+ ) {+ SelectionMenuItem(Icons.Rounded.ContentCopy, "Copy", menuFg) {+ onCopySelection(); onClearOcrSelection()+ }+ SelectionMenuItem(Icons.Rounded.SelectAll, "Select all", menuFg) { onSelectAll() }+ SelectionMenuItem(+ Icons.Rounded.Highlight,+ if (selectionHasHighlight) "Recolor" else "Highlight",+ if (selectionHasHighlight) currentColor else menuFg+ ) { onHighlightSelection() }+ SelectionMenuItem(Icons.Rounded.FormatUnderlined, "Underline", menuFg) { onUnderlineSelection() }+ SelectionMenuItem(Icons.Rounded.StrikethroughS, "Strike", menuFg) { onStrikeSelection() }+ if (selectionHasHighlight) {+ SelectionMenuItem(Icons.Rounded.Delete, "Delete", Color(0xFFEF5350)) {+ // Drop every highlight sitting on a selected word, then clear the+ // selection so the menu dismisses.+ marks.removeAll { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId in selectedOcrIds }+ onClearOcrSelection()+ }+ }+ }+ Box(Modifier.fillMaxWidth().height(1.dp).background(Color.White.copy(0.08f)))+ Row(+ Modifier+ .padding(horizontal = 10.dp, vertical = 8.dp)+ .horizontalScroll(rememberScrollState()),+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ verticalAlignment = Alignment.CenterVertically+ ) {+ editorPalette.forEach { c ->+ val isSel = c.value == currentColor.value+ Box(+ Modifier+ .size(16.dp)+ .clip(CircleShape)+ .background(c)+ .border(+ width = if (isSel) 2.dp else 0.dp,+ color = Color.White.copy(0.85f),+ shape = CircleShape+ )+ .clickable { onSetColorLong(c.value.toLong()) }+ )+ }}}}@@ -802,7 +853,7 @@ internal fun PdfContinuousPage(val density = LocalDensity.currentval gapPx = with(density) { 10.dp.toPx() }val barHpx = with(density) { 44.dp.toPx() }- val barWpx = with(density) { 96.dp.toPx() }+ val barWpx = with(density) { 176.dp.toPx() }val placeBelow = anchorRect.top < barHpx + gapPxval by = (if (placeBelow) anchorRect.bottom + gapPx else anchorRect.top - barHpx - gapPx).coerceIn(0f, (csz.height - barHpx).coerceAtLeast(0f))@@ -812,19 +863,29 @@ internal fun PdfContinuousPage(Row(Modifier.offset { IntOffset(bx.roundToInt(), by.roundToInt()) }- .clip(RoundedCornerShape(22.dp))- .background(Color(0xFF1C1F26).copy(0.97f))- .border(1.dp, Color.White.copy(0.14f), RoundedCornerShape(22.dp))- .padding(horizontal = 4.dp, vertical = 3.dp),+ .clip(RoundedCornerShape(10.dp))+ .background(Color(0xFF232629))+ .border(1.dp, Color.White.copy(0.08f), RoundedCornerShape(10.dp))+ .padding(horizontal = 2.dp, vertical = 2.dp),verticalAlignment = Alignment.CenterVertically) {+ // Same Edit affordance as shapes/text/notes — opens the shared recolor+ // popover (ShapeEditorPopup handles highlight/underline/strike too).+ BasicText(+ "Edit",+ style = TextStyle(Color(0xFFECECEC), 13.sp, FontWeight.Medium),+ modifier = Modifier+ .clip(RoundedCornerShape(6.dp))+ .clickable { onEditShape(selectedMarkupIndex) }+ .padding(horizontal = 16.dp, vertical = 10.dp)+ )BasicText("Delete",- style = TextStyle(Color(0xFFFF6B6B), 13.sp, FontWeight.SemiBold),+ style = TextStyle(Color(0xFFEF5350), 13.sp, FontWeight.Medium),modifier = Modifier- .clip(RoundedCornerShape(18.dp))+ .clip(RoundedCornerShape(6.dp)).clickable { onDeleteMarkup(selectedMarkupIndex) }- .padding(horizontal = 16.dp, vertical = 9.dp)+ .padding(horizontal = 16.dp, vertical = 10.dp))}}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerBottomToolbar.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerBottomToolbar.ktindex 77ada9a..dd774e1 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerBottomToolbar.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerBottomToolbar.kt@@ -367,20 +367,22 @@ internal fun PdfViewerBottomToolbar(}showOcrTools -> {+ // Plain, native-menu-style neutral buttons — no per-action rainbow+ // tinting — matching the in-context selection toolbar's look.LiquidButton(onClick = onSelectAllText, backdrop = backdrop, surfaceColor = chip) {BasicText(stringResource(R.string.viewer_select_all), style = TextStyle(fg, 12.sp, FontWeight.Medium))}- LiquidButton(onClick = onCopyText, backdrop = backdrop, tint = Color(0xFF7E57C2)) {- BasicText(stringResource(R.string.copy), style = TextStyle(Color.White, 12.sp, FontWeight.Medium))+ LiquidButton(onClick = onCopyText, backdrop = backdrop, surfaceColor = chip) {+ BasicText(stringResource(R.string.copy), style = TextStyle(fg, 12.sp, FontWeight.Medium))}- LiquidButton(onClick = onHighlightSelected, backdrop = backdrop, tint = Color(0xFFFFB300)) {- BasicText(stringResource(R.string.viewer_highlight), style = TextStyle(Color.White, 12.sp, FontWeight.Medium))+ LiquidButton(onClick = onHighlightSelected, backdrop = backdrop, surfaceColor = chip) {+ BasicText(stringResource(R.string.viewer_highlight), style = TextStyle(fg, 12.sp, FontWeight.Medium))}- LiquidButton(onClick = onUnderlineSelected, backdrop = backdrop, tint = Color(0xFF4CAF50)) {- BasicText(stringResource(R.string.viewer_underline), style = TextStyle(Color.White, 12.sp, FontWeight.Medium))+ LiquidButton(onClick = onUnderlineSelected, backdrop = backdrop, surfaceColor = chip) {+ BasicText(stringResource(R.string.viewer_underline), style = TextStyle(fg, 12.sp, FontWeight.Medium))}- LiquidButton(onClick = onStrikeSelected, backdrop = backdrop, tint = Color(0xFFEF5350)) {- BasicText(stringResource(R.string.viewer_strike), style = TextStyle(Color.White, 12.sp, FontWeight.Medium))+ LiquidButton(onClick = onStrikeSelected, backdrop = backdrop, surfaceColor = chip) {+ BasicText(stringResource(R.string.viewer_strike), style = TextStyle(fg, 12.sp, FontWeight.Medium))}LiquidButton(onClick = onClearTextSelection, backdrop = backdrop, surfaceColor = chip) {BasicText(stringResource(R.string.viewer_clear), style = TextStyle(fg, 12.sp, FontWeight.Medium))diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.ktindex 0321c7b..3d062a3 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt@@ -149,6 +149,10 @@ internal sealed class PdfMarkup {internal fun PdfMarkup.isShape(): Boolean = this is PdfMarkup.StrokeMarkup ||this is PdfMarkup.RectMarkup || this is PdfMarkup.OvalMarkup || this is PdfMarkup.LineMarkup+/** Anything [ShapeEditorPopup] can recolour — shapes plus OCR-anchored highlight/underline/strike. */+internal fun PdfMarkup.isRecolorable(): Boolean = isShape() ||+ this is PdfMarkup.TextBlockHighlightMarkup || this is PdfMarkup.TextBlockLineMarkup+/** Markups that support the generic select → move / resize transform (everything the user* places freely, except images which have their own dedicated toolbar path). */internal fun PdfMarkup.isTransformable(): Boolean = this is PdfMarkup.StrokeMarkup ||@@ -227,6 +231,8 @@ internal fun PdfMarkup.shapeColor(): Color = when (this) {is PdfMarkup.RectMarkup -> coloris PdfMarkup.OvalMarkup -> coloris PdfMarkup.LineMarkup -> color+ is PdfMarkup.TextBlockHighlightMarkup -> color+ is PdfMarkup.TextBlockLineMarkup -> colorelse -> Color(0xFF1976D2)}@@ -235,6 +241,8 @@ internal fun PdfMarkup.recolored(c: Color): PdfMarkup = when (this) {is PdfMarkup.RectMarkup -> copy(color = c)is PdfMarkup.OvalMarkup -> copy(color = c)is PdfMarkup.LineMarkup -> copy(color = c)+ is PdfMarkup.TextBlockHighlightMarkup -> copy(color = c)+ is PdfMarkup.TextBlockLineMarkup -> copy(color = c)else -> this}@@ -420,6 +428,32 @@ internal fun ocrSelectionHandleAnchors(return Offset(firstRect.left, firstRect.bottom) to Offset(lastRect.right, lastRect.bottom)}+/**+ * Rendered line height (in the same canvas-local pixels as [ocrSelectionHandleAnchors]'s+ * anchors) for the first/last selected line. The page is drawn at whatever zoom/fit-width+ * scale is currently active, so a FIXED dp handle size looks tiny at 200% zoom and gigantic+ * at fit-width (a full page's line height can be under 20px there) — handles must scale with+ * the text they're anchored to, exactly like the platform text selector's do.+ */+internal fun ocrSelectionHandleLineHeights(+ blocks: List<OcrTextBlock>,+ ranges: List<OcrTextRange>,+ frame: Rect+): Pair<Float, Float>? {+ if (ranges.isEmpty()) return null+ val blocksById = blocks.associateBy { it.id }+ val ordered = ranges.sortedWith(+ compareBy<OcrTextRange>(+ { blocksById[it.blockId]?.top ?: Float.MAX_VALUE },+ { blocksById[it.blockId]?.left ?: Float.MAX_VALUE },+ { it.start }+ )+ )+ val firstBlock = blocksById[ordered.first().blockId] ?: return null+ val lastBlock = blocksById[ordered.last().blockId] ?: return null+ return (firstBlock.bottom - firstBlock.top) * frame.height to (lastBlock.bottom - lastBlock.top) * frame.height+}+/** Custom organic handle used by the PDF selection layer; deliberately not a platform handle. */internal fun DrawScope.drawTextSelectionHandle(anchor: Offset,diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.ktindex 206b6fc..22f61db 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerScreen.kt@@ -558,6 +558,12 @@ fun PdfViewerScreen(val safePageCount = state.pageCount.coerceAtLeast(1)val viewerScope = rememberCoroutineScope()val currentPageIndex = listState.firstVisibleItemIndex.coerceIn(0, safePageCount - 1)+ // The bottom SelectText toolbar must act on whichever page actually holds the current OCR+ // selection, not the viewport-derived currentPageIndex — otherwise scrolling after selecting+ // (or the selection sitting on a page whose bottom sliver is visible, not its top) makes+ // Highlight/Underline/Strike/Copy silently target the wrong page's empty selection.+ val selectionPageIndex = state.selectedOcrRangesByPage.entries+ .firstOrNull { it.value.isNotEmpty() }?.key ?: currentPageIndex// Live backdrop that captures the ACTUAL rendered page column (dark bg + PDF// pages), so the glass chrome reflects real content instead of the static@@ -917,11 +923,33 @@ fun PdfViewerScreen(// range so a re-tap replaces the colour instead of stacking layers.m.removeAll { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end }m.add(PdfMarkup.TextBlockHighlightMarkup(range.blockId, Color(currentColorLong), 0.38f, range.start, range.end))+ recordEdit(page)}// Keep the selection live so the pill immediately offers Recolor / Delete —// this is the fix for "after highlighting there's no delete option".lastInteractionAtMs = System.currentTimeMillis()},+ onUnderlineSelection = {+ val m = getPageMarks(page)+ selectedTextRanges(page).forEach { range ->+ if (!m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end && !it.strikeThrough }) {+ m.add(PdfMarkup.TextBlockLineMarkup(range.blockId, Color(currentColorLong), 3f, 1f, false, range.start, range.end))+ recordEdit(page)+ }+ }+ lastInteractionAtMs = System.currentTimeMillis()+ },+ onStrikeSelection = {+ val m = getPageMarks(page)+ selectedTextRanges(page).forEach { range ->+ if (!m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end && it.strikeThrough }) {+ m.add(PdfMarkup.TextBlockLineMarkup(range.blockId, Color(currentColorLong), 3f, 1f, true, range.start, range.end))+ recordEdit(page)+ }+ }+ lastInteractionAtMs = System.currentTimeMillis()+ },+ onSetColorLong = { currentColorLong = it },onSelectAll = {val ids = state.ocrBlocksByPage[page].orEmpty().map { it.id }.toSet()if (ids.isNotEmpty()) viewModel.selectOcrBlocks(page, ids, append = false)@@ -1092,31 +1120,34 @@ fun PdfViewerScreen(if (ids.isNotEmpty()) viewModel.selectOcrBlocks(currentPageIndex, ids, false)},onCopyText = {- viewModel.getSelectedOcrText(currentPageIndex).takeIf { it.isNotBlank() }+ viewModel.getSelectedOcrText(selectionPageIndex).takeIf { it.isNotBlank() }?.let { clipboard.setText(AnnotatedString(it)) }},onHighlightSelected = {- val m = getPageMarks(currentPageIndex)- selectedTextRanges(currentPageIndex).forEach { range ->+ val m = getPageMarks(selectionPageIndex)+ selectedTextRanges(selectionPageIndex).forEach { range ->if (!m.any { it is PdfMarkup.TextBlockHighlightMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end })m.add(PdfMarkup.TextBlockHighlightMarkup(range.blockId, Color(currentColorLong), 0.38f, range.start, range.end))+ recordEdit(selectionPageIndex)}},onUnderlineSelected = {- val m = getPageMarks(currentPageIndex)- selectedTextRanges(currentPageIndex).forEach { range ->+ val m = getPageMarks(selectionPageIndex)+ selectedTextRanges(selectionPageIndex).forEach { range ->if (!m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end && !it.strikeThrough })m.add(PdfMarkup.TextBlockLineMarkup(range.blockId, Color(currentColorLong), 3f, 1f, false, range.start, range.end))+ recordEdit(selectionPageIndex)}},onStrikeSelected = {- val m = getPageMarks(currentPageIndex)- selectedTextRanges(currentPageIndex).forEach { range ->+ val m = getPageMarks(selectionPageIndex)+ selectedTextRanges(selectionPageIndex).forEach { range ->if (!m.any { it is PdfMarkup.TextBlockLineMarkup && it.blockId == range.blockId && it.start == range.start && it.end == range.end && it.strikeThrough })m.add(PdfMarkup.TextBlockLineMarkup(range.blockId, Color(currentColorLong), 3f, 1f, true, range.start, range.end))+ recordEdit(selectionPageIndex)}},- onClearTextSelection = { viewModel.clearOcrSelection(currentPageIndex) },+ onClearTextSelection = { viewModel.clearOcrSelection(selectionPageIndex) },onSetColorLong = { currentColorLong = it },onSetStrokeWidth = { currentStrokeWidth = it },onDismissExportFeedback = { viewModel.clearExportFeedback() },@@ -1233,7 +1264,7 @@ fun PdfViewerScreen(editingShapePage?.let { shapePage ->val list = getPageMarks(shapePage)val shape = list.getOrNull(editingShapeIndex)- if (shape != null && shape.isShape()) {+ if (shape != null && shape.isRecolorable()) {ShapeEditorPopup(initialColor = shape.shapeColor(),backdrop = contentBackdrop,@@ -1244,7 +1275,7 @@ fun PdfViewerScreen(field = chromeField,onColorChange = { c ->val cur = list.getOrNull(editingShapeIndex)- if (cur != null && cur.isShape()) list[editingShapeIndex] = cur.recolored(c)+ if (cur != null && cur.isRecolorable()) list[editingShapeIndex] = cur.recolored(c)lastInteractionAtMs = System.currentTimeMillis()},onDelete = {diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ExtractTextViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ExtractTextViewModel.ktindex 450c5d8..6c2b69a 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ExtractTextViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ExtractTextViewModel.kt@@ -1,33 +1,68 @@package com.chethan616.clearpdf.ui.viewmodel+import android.content.ContentValuesimport android.content.Contextimport android.content.Intentimport android.net.Uri+import android.os.Build+import android.os.Environment+import android.provider.MediaStore+import androidx.core.content.FileProviderimport androidx.lifecycle.ViewModelimport androidx.lifecycle.viewModelScope-import com.kyant.pdfcore.converter.PdfConverterimport com.chethan616.clearpdf.R+import com.chethan616.clearpdf.data.repository.RecentFile+import com.chethan616.clearpdf.data.repository.RecentFilesManager+import com.chethan616.clearpdf.data.repository.SaveLocationManager+import com.kyant.ocrcore.OcrService+import com.kyant.ocrcore.OcrWord+import com.kyant.pdfcore.converter.PdfConverterimport com.kyant.pdfcore.model.PdfDocument+import com.kyant.pdfcore.raster.PdfRasterizer+import com.kyant.pdfcore.searchable.InvisibleWord+import com.kyant.pdfcore.searchable.PdfSearchableStamper+import com.kyant.pdfcore.viewer.PdfViewerimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Localedata class ExtractTextUiState(val sourceFileName: String = "",+ val sourceUri: Uri? = null,val isExtracting: Boolean = false,val text: String = "",val hasResult: Boolean = false,- val errorMessage: String? = null+ val errorMessage: String? = null,+ /** True once extraction found no digital text layer — offers the OCR fallback. */+ val canRecognize: Boolean = false,+ val isRecognizing: Boolean = false,+ val recognizeProgress: Pair<Int, Int>? = null,+ /** True once OCR has produced word boxes that can be baked into a searchable PDF. */+ val canMakeSearchable: Boolean = false,+ val isSavingSearchable: Boolean = false,+ val searchableOutputUri: Uri? = null,+ val searchableSavedLabel: String? = null)-class ExtractTextViewModel(private val converter: PdfConverter) : ViewModel() {+class ExtractTextViewModel(+ private val converter: PdfConverter,+ private val ocrService: OcrService,+ private val pdfViewer: PdfViewer+) : ViewModel() {private val _uiState = MutableStateFlow(ExtractTextUiState())val uiState: StateFlow<ExtractTextUiState> = _uiState.asStateFlow()+ /** Word boxes from the last OCR pass, kept so "Make Searchable" doesn't need to re-run OCR. */+ private var lastOcrWordsByPage: Map<Int, List<OcrWord>> = emptyMap()+fun onSelectFile(context: Context, uri: Uri) {+ lastOcrWordsByPage = emptyMap()_uiState.value = ExtractTextUiState(isExtracting = true)viewModelScope.launch {try {@@ -37,14 +72,15 @@ class ExtractTextViewModel(private val converter: PdfConverter) : ViewModel() {val name = queryFileName(context, uri) ?: "Unknown.pdf"val source = PdfDocument(uri = uri, name = name)val extracted = withContext(Dispatchers.IO) { converter.extractText(context, source) }.trim()+ val empty = extracted.isEmpty()_uiState.value = ExtractTextUiState(sourceFileName = name,+ sourceUri = uri,isExtracting = false,text = extracted,hasResult = true,- errorMessage = if (extracted.isEmpty())- context.getString(R.string.extract_no_selectable_text)- else null+ canRecognize = empty,+ errorMessage = if (empty) context.getString(R.string.extract_no_selectable_text) else null)} catch (e: Exception) {_uiState.value = ExtractTextUiState(isExtracting = false, errorMessage = context.getString(R.string.text_extraction_failed))@@ -52,7 +88,92 @@ class ExtractTextViewModel(private val converter: PdfConverter) : ViewModel() {}}+ /**+ * Fallback for scanned/image-only PDFs: runs on-device OCR page by page (ML Kit,+ * falling back to Tesseract4Android) and joins the recognized text, closing the+ * "no selectable text" dead end left by pure PdfBox extraction.+ */+ fun recognizeText(context: Context) {+ val uri = _uiState.value.sourceUri ?: return+ if (_uiState.value.isRecognizing) return+ _uiState.value = _uiState.value.copy(isRecognizing = true, recognizeProgress = null)+ viewModelScope.launch {+ val wordsByPage = mutableMapOf<Int, List<OcrWord>>()+ val result = withContext(Dispatchers.IO) {+ val doc = runCatching { pdfViewer.open(context, uri) }.getOrNull()+ val pageCount = doc?.pageCount?.takeIf { it > 0 } ?: 0+ doc?.let { runCatching { pdfViewer.close(it) } }+ if (pageCount == 0) return@withContext ""++ val pages = mutableListOf<String>()+ for (i in 0 until pageCount) {+ // MutableStateFlow.value is safe to set from any thread.+ _uiState.value = _uiState.value.copy(recognizeProgress = i to pageCount)+ val bitmap = runCatching { PdfRasterizer.rasterizePageBitmap(context, uri, i) }.getOrNull()+ if (bitmap != null) {+ val words = runCatching { ocrService.recognize(context, bitmap) }.getOrNull()?.words.orEmpty()+ if (words.isNotEmpty()) {+ wordsByPage[i] = words+ pages.add(words.joinToString(" ") { it.text })+ }+ if (!bitmap.isRecycled) bitmap.recycle()+ }+ }+ pages.joinToString("\n\n")+ }+ lastOcrWordsByPage = wordsByPage+ val trimmed = result.trim()+ _uiState.value = _uiState.value.copy(+ isRecognizing = false,+ recognizeProgress = null,+ text = trimmed,+ hasResult = true,+ canRecognize = false,+ canMakeSearchable = wordsByPage.isNotEmpty(),+ errorMessage = if (trimmed.isEmpty()) context.getString(R.string.extract_no_selectable_text) else null+ )+ }+ }++ /** Bakes the last OCR pass's word boxes into a copy of the source PDF as an invisible,+ * selectable/searchable text layer — readable in any PDF viewer, not just ClearPDF. */+ fun makeSearchablePdf(context: Context) {+ val uri = _uiState.value.sourceUri ?: return+ val wordsByPage = lastOcrWordsByPage+ if (wordsByPage.isEmpty() || _uiState.value.isSavingSearchable) return+ _uiState.value = _uiState.value.copy(isSavingSearchable = true, errorMessage = null, searchableOutputUri = null)+ viewModelScope.launch {+ try {+ val invisibleWordsByPage = wordsByPage.mapValues { (_, words) ->+ words.map { InvisibleWord(it.text, it.left, it.top, it.right, it.bottom) }+ }+ val ts = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())+ val fileName = "ClearPDF_Searchable_$ts.pdf"+ val saveLabel = SaveLocationManager.getSavePathDisplay(context)+ val outUri = createOutputUri(context, fileName)+ withContext(Dispatchers.IO) {+ PdfSearchableStamper.stamp(context, uri, outUri, invisibleWordsByPage)+ }+ RecentFilesManager.addRecent(+ context,+ RecentFile(name = fileName, uriString = outUri.toString(), timestamp = System.currentTimeMillis(), sizeBytes = 0)+ )+ _uiState.value = _uiState.value.copy(+ isSavingSearchable = false,+ searchableOutputUri = outUri,+ searchableSavedLabel = saveLabel+ )+ } catch (t: Throwable) {+ _uiState.value = _uiState.value.copy(+ isSavingSearchable = false,+ errorMessage = t.message ?: "Couldn't create a searchable PDF"+ )+ }+ }+ }+fun reset() {+ lastOcrWordsByPage = emptyMap()_uiState.value = ExtractTextUiState()}@@ -64,4 +185,33 @@ class ExtractTextViewModel(private val converter: PdfConverter) : ViewModel() {} else null}} catch (_: Exception) { null }++ private fun createOutputUri(context: Context, fileName: String): Uri {+ val customUri = SaveLocationManager.getSaveUri(context)+ if (customUri != null) {+ return try {+ val docUri = androidx.documentfile.provider.DocumentFile.fromTreeUri(context, customUri)+ docUri?.createFile("application/pdf", fileName)?.uri ?: createDownloadUri(context, fileName)+ } catch (_: Exception) { createDownloadUri(context, fileName) }+ }+ return createDownloadUri(context, fileName)+ }++ private fun createDownloadUri(context: Context, fileName: String): Uri {+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ val cv = ContentValues().apply {+ put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)+ put(MediaStore.MediaColumns.MIME_TYPE, "application/pdf")+ put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)+ }+ context.contentResolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, cv)+ ?: throw IllegalStateException("Unable to create output in Downloads")+ } else {+ val dir = context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) ?: context.filesDir+ if (!dir.exists()) dir.mkdirs()+ val file = java.io.File(dir, fileName)+ if (!file.exists()) file.createNewFile()+ FileProvider.getUriForFile(context, "${context.packageName}.provider", file)+ }+ }}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/OcrPageCache.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/OcrPageCache.ktnew file mode 100644index 0000000..587c9de--- /dev/null+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/OcrPageCache.kt@@ -0,0 +1,129 @@+package com.chethan616.clearpdf.ui.viewmodel++import android.content.Context+import com.kyant.ocrcore.OcrWord+import com.kyant.pdfcore.model.PdfDocument+import java.io.File+import java.security.MessageDigest+import kotlin.math.abs+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Disk cache for on-device OCR results, keyed by document identity + page index.+ * OCR (especially the Tesseract fallback) is too slow to re-run every time a scanned+ * PDF is reopened, so a successful recognition is persisted once under the app cache dir.+ */+internal object OcrPageCache {+ private val json = Json { ignoreUnknownKeys = true }++ private fun docKey(doc: PdfDocument): String {+ val raw = "${doc.uri}|${doc.sizeBytes}"+ val digest = MessageDigest.getInstance("SHA-256").digest(raw.toByteArray())+ return digest.joinToString("") { "%02x".format(it) }+ }++ private fun cacheFile(context: Context, doc: PdfDocument, pageIndex: Int): File {+ val dir = File(context.cacheDir, "ocr_cache/${docKey(doc)}").apply { mkdirs() }+ return File(dir, "page_$pageIndex.json")+ }++ fun read(context: Context, doc: PdfDocument, pageIndex: Int): List<OcrTextBlock>? {+ val file = cacheFile(context, doc, pageIndex)+ if (!file.exists()) return null+ return runCatching {+ json.decodeFromString<CachedOcrPage>(file.readText()).blocks.map { it.toOcrBlock() }+ }.getOrNull()+ }++ fun write(context: Context, doc: PdfDocument, pageIndex: Int, blocks: List<OcrTextBlock>) {+ runCatching {+ val page = CachedOcrPage(blocks.map { it.toCached() })+ cacheFile(context, doc, pageIndex).writeText(json.encodeToString(CachedOcrPage.serializer(), page))+ }+ }+}++@Serializable+private data class CachedOcrPage(val blocks: List<CachedOcrBlock>)++@Serializable+private data class CachedOcrBlock(+ val id: String,+ val text: String,+ val left: Float,+ val top: Float,+ val right: Float,+ val bottom: Float,+ val charLefts: List<Float>,+ val charRights: List<Float>+)++private fun OcrTextBlock.toCached() = CachedOcrBlock(+ id = id, text = text, left = left, top = top, right = right, bottom = bottom,+ charLefts = charLefts.toList(), charRights = charRights.toList()+)++private fun CachedOcrBlock.toOcrBlock() = OcrTextBlock(+ id = id, text = text, left = left, top = top, right = right, bottom = bottom,+ charLefts = charLefts.toFloatArray(), charRights = charRights.toFloatArray()+)++/**+ * Groups flat OCR word boxes (from [com.kyant.ocrcore.OcrService]) back into line-shaped+ * [OcrTextBlock]s, mirroring [com.kyant.pdfcore.text.PdfTextService]'s character-stream+ * grouping so the rest of the viewer (selection sweep, search, highlight) is fully generic+ * over the two text sources and needs no OCR-specific branching.+ */+internal fun groupOcrWordsIntoBlocks(words: List<OcrWord>, pageIndex: Int): List<OcrTextBlock> {+ if (words.isEmpty()) return emptyList()++ val avgH = words.map { it.bottom - it.top }.average().toFloat().coerceAtLeast(0.005f)+ val lineGap = avgH * 0.6f++ val sorted = words.sortedBy { (it.top + it.bottom) / 2f }+ val lines = mutableListOf<MutableList<OcrWord>>()+ for (w in sorted) {+ val cy = (w.top + w.bottom) / 2f+ val last = lines.lastOrNull()+ val lastCy = last?.let { l -> l.map { (it.top + it.bottom) / 2f }.average().toFloat() }+ if (last == null || lastCy == null || abs(cy - lastCy) > lineGap) {+ lines.add(mutableListOf(w))+ } else {+ last.add(w)+ }+ }++ return lines.mapIndexedNotNull { lineIdx, lineWords ->+ val byX = lineWords.sortedBy { it.left }+ val sb = StringBuilder()+ val cl = ArrayList<Float>()+ val cr = ArrayList<Float>()+ var lastRight = -1f+ byX.forEach { w ->+ if (lastRight >= 0f) {+ // Words are already tokenized by the OCR engine — always separate them with+ // a space, unlike the PDFBox char-stream path which must infer word breaks.+ sb.append(' '); cl.add(lastRight); cr.add(w.left)+ }+ val n = w.text.length.coerceAtLeast(1)+ for (i in w.text.indices) {+ sb.append(w.text[i])+ cl.add(w.left + (w.right - w.left) * i / n)+ cr.add(w.left + (w.right - w.left) * (i + 1) / n)+ }+ lastRight = w.right+ }+ if (sb.isEmpty()) return@mapIndexedNotNull null+ OcrTextBlock(+ id = "$pageIndex-ocr-$lineIdx",+ text = sb.toString(),+ left = byX.minOf { it.left },+ top = byX.minOf { it.top },+ right = byX.maxOf { it.right },+ bottom = byX.maxOf { it.bottom },+ charLefts = cl.toFloatArray(),+ charRights = cr.toFloatArray()+ )+ }+}diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.ktindex 4c8e138..b18c5a3 100644--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt@@ -25,6 +25,7 @@ import com.chethan616.clearpdf.ui.utils.AppDispatchersimport com.chethan616.clearpdf.ui.utils.StarPromptEventBusimport com.chethan616.clearpdf.utils.UniversalDocumentConverterimport com.kyant.pdfcore.model.PdfDocument+import com.kyant.pdfcore.raster.PdfRasterizerimport com.kyant.pdfcore.security.PdfSecurityServiceimport com.kyant.pdfcore.text.PdfTextBlockimport kotlinx.coroutines.Dispatchers@@ -415,13 +416,20 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel)viewModelScope.launch {- val blocks = withContext(Dispatchers.IO) {+ val blocks = withContext(AppDispatchers.pdf) {// One full-document PdfBox parse at a time — see [textExtractionMutex].- textExtractionMutex.withLock {+ val pdfBlocks = textExtractionMutex.withLock {runCatching {textService.extractPage(context, doc.uri, pageIndex)}.getOrElse { emptyList() }}+ if (pdfBlocks.isNotEmpty()) {+ pdfBlocks.map { it.toOcrBlock() }+ } else {+ // No digital text layer (scanned/image-only page) — fall back to+ // on-device OCR, cached to disk so re-opening the doc is instant.+ loadOcrFallbackBlocks(context, doc, pageIndex)+ }}val current = _uiState.valueif (current.document?.uri != doc.uri) {@@ -429,7 +437,7 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModelreturn@launch}val updated = current.ocrBlocksByPage.toMutableMap()- updated[pageIndex] = blocks.map { it.toOcrBlock() }+ updated[pageIndex] = blockstextLoadingPages.remove(pageIndex)_uiState.value = current.copy(ocrBlocksByPage = updated,@@ -438,6 +446,23 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel}}+ /** Rasterizes [pageIndex] and runs it through [PdfServiceLocator.ocrService], reading/writing the disk cache. */+ private suspend fun loadOcrFallbackBlocks(context: Context, doc: PdfDocument, pageIndex: Int): List<OcrTextBlock> {+ OcrPageCache.read(context, doc, pageIndex)?.let { return it }+ val bitmap = runCatching {+ PdfRasterizer.rasterizePageBitmap(context, doc.uri, pageIndex)+ }.getOrNull() ?: return emptyList()+ return try {+ val result = runCatching { PdfServiceLocator.ocrService.recognize(context, bitmap) }.getOrNull()+ ?: return emptyList()+ val blocks = groupOcrWordsIntoBlocks(result.words, pageIndex)+ OcrPageCache.write(context, doc, pageIndex, blocks)+ blocks+ } finally {+ if (!bitmap.isRecycled) bitmap.recycle()+ }+ }+fun onPageChanged(page: Int) {val state = _uiState.valueif (page !in state.pageBitmaps.indices) returndiff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xmlindex 75e35a6..d66ab05 100644--- a/app/src/main/res/values-pt-rBR/strings.xml+++ b/app/src/main/res/values-pt-rBR/strings.xml@@ -421,7 +421,11 @@<string name="create_failed">Falha ao criar o PDF.</string><string name="compression_success">Comprimido: %1$dKB -> %2$dKB (%3$d%% menor)\nSalvo em %4$s</string><string name="compression_failed">Falha ao comprimir.</string>- <string name="extract_no_selectable_text">Nenhum texto selecionável encontrado. Este PDF pode ser uma digitalização ou imagem - tente o OCR do scanner.</string>+ <string name="extract_no_selectable_text">Nenhum texto selecionável encontrado. Este PDF parece ser uma digitalização ou imagem — toque em Reconhecer Texto para OCR no dispositivo.</string>+ <string name="extract_recognize_text">Reconhecer Texto (OCR)</string>+ <string name="extract_recognizing">Reconhecendo texto… (%1$d/%2$d)</string>+ <string name="extract_make_searchable">Salvar como PDF Pesquisável</string>+ <string name="extract_searchable_saved">PDF pesquisável salvo · %1$s</string><string name="text_extraction_failed">Falha ao extrair o texto.</string><string name="organize_open_failed">Não foi possível abrir o PDF.</string><string name="organize_cannot_delete_all">Não é possível excluir todas as páginas.</string>diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xmlindex 7fc6850..0f5b3a5 100644--- a/app/src/main/res/values-pt/strings.xml+++ b/app/src/main/res/values-pt/strings.xml@@ -421,7 +421,11 @@<string name="create_failed">Falha ao criar o PDF.</string><string name="compression_success">Comprimido: %1$dKB -> %2$dKB (%3$d%% menor)\nSalvo em %4$s</string><string name="compression_failed">Falha ao comprimir.</string>- <string name="extract_no_selectable_text">Nenhum texto selecionável encontrado. Este PDF pode ser uma digitalização ou imagem - tente o OCR do scanner.</string>+ <string name="extract_no_selectable_text">Nenhum texto selecionável encontrado. Este PDF parece ser uma digitalização ou imagem — toque em Reconhecer Texto para OCR no dispositivo.</string>+ <string name="extract_recognize_text">Reconhecer Texto (OCR)</string>+ <string name="extract_recognizing">Reconhecendo texto… (%1$d/%2$d)</string>+ <string name="extract_make_searchable">Salvar como PDF Pesquisável</string>+ <string name="extract_searchable_saved">PDF pesquisável salvo · %1$s</string><string name="text_extraction_failed">Falha ao extrair o texto.</string><string name="organize_open_failed">Não foi possível abrir o PDF.</string><string name="organize_cannot_delete_all">Não é possível excluir todas as páginas.</string>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex e9dfd1d..b635583 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -502,7 +502,11 @@<string name="create_failed">Failed to create PDF.</string><string name="compression_success">Compressed: %1$dKB -> %2$dKB (%3$d%% smaller)\nSaved to %4$s</string><string name="compression_failed">Compression failed.</string>- <string name="extract_no_selectable_text">No selectable text found. This PDF may be a scan or image - try the scanner OCR instead.</string>+ <string name="extract_no_selectable_text">No selectable text found. This PDF looks like a scan or image — tap Recognize Text to run on-device OCR.</string>+ <string name="extract_recognize_text">Recognize Text (OCR)</string>+ <string name="extract_recognizing">Recognizing text… (%1$d/%2$d)</string>+ <string name="extract_make_searchable">Save as Searchable PDF</string>+ <string name="extract_searchable_saved">Saved searchable PDF · %1$s</string><string name="text_extraction_failed">Text extraction failed.</string><string name="organize_open_failed">Could not open PDF.</string><string name="organize_cannot_delete_all">Cannot delete every page.</string>diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex c53ac3c..25b3323 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -17,6 +17,8 @@ camerax = "1.4.1"coil = "3.0.4"accompanist = "0.36.0"pdfbox = "2.0.27.0"+kotlinxCoroutines = "1.10.2"+tesseract4android = "4.9.0"[libraries]kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" }@@ -36,7 +38,6 @@ androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lif# ML Kit & Scanningplay-services-mlkit-scanner = { group = "com.google.android.gms", name = "play-services-mlkit-document-scanner", version.ref = "mlkit" }-play-services-mlkit-text-recognition = { group = "com.google.android.gms", name = "play-services-mlkit-text-recognition", version = "19.0.1" }camerax-core = { group = "androidx.camera", name = "camera-core", version.ref = "camerax" }camerax-camera2 = { group = "androidx.camera", name = "camera-camera2", version.ref = "camerax" }camerax-lifecycle = { group = "androidx.camera", name = "camera-lifecycle", version.ref = "camerax" }@@ -44,6 +45,11 @@ camerax-view = { group = "androidx.camera", name = "camera-view", version.ref =coil-compose = { group = "io.coil-kt.coil3", name = "coil-compose", version.ref = "coil" }acccompanist-permissions = { group = "com.google.accompanist", name = "accompanist-permissions", version.ref = "accompanist" }+# OCR (fully on-device — see ocr-core module + THIRD_PARTY_NOTICES.md)+kotlinx-coroutines-core = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" }+mlkit-text-recognition = { group = "com.google.mlkit", name = "text-recognition", version.ref = "mlkitTextRecognition" }+tesseract4android = { group = "cz.adaptech.tesseract4android", name = "tesseract4android", version.ref = "tesseract4android" }+[plugins]android-application = { id = "com.android.application", version.ref = "agp" }android-library = { id = "com.android.library", version.ref = "agp" }diff --git a/ocr-core/build.gradle.kts b/ocr-core/build.gradle.ktsnew file mode 100644index 0000000..8a3927f--- /dev/null+++ b/ocr-core/build.gradle.kts@@ -0,0 +1,48 @@+plugins {+ alias(libs.plugins.android.library)+}++android {+ namespace = "com.kyant.ocrcore"+ compileSdk {+ version = release(36)+ }+ buildToolsVersion = "36.1.0"++ defaultConfig {+ minSdk = 23+ consumerProguardFiles("consumer-rules.pro")+ }++ buildTypes {+ release {+ isMinifyEnabled = false+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")+ }+ }++ packaging {+ // Tesseract4Android ships its own .so per ABI; nothing to exclude by default,+ // but keep resources.excludes future-proof against META-INF collisions like pdf-core.+ resources {+ excludes += arrayOf("META-INF/LICENSE", "META-INF/LICENSE.md", "META-INF/NOTICE", "META-INF/NOTICE.md")+ }+ }+}++kotlin {+ jvmToolchain(21)+}++dependencies {+ implementation(libs.androidx.core.ktx)+ implementation(libs.kotlinx.coroutines.core)++ // Bundled (no Play Services / no network) on-device OCR — primary engine.+ // See THIRD_PARTY_NOTICES.md.+ implementation(libs.mlkit.text.recognition)++ // Fully open-source (Apache-2.0) offline OCR fallback for devices where the+ // bundled ML Kit model fails to initialize. See THIRD_PARTY_NOTICES.md.+ implementation(libs.tesseract4android)+}diff --git a/ocr-core/consumer-rules.pro b/ocr-core/consumer-rules.pronew file mode 100644index 0000000..68db37f--- /dev/null+++ b/ocr-core/consumer-rules.pro@@ -0,0 +1,7 @@+# ML Kit Text Recognition — keep classes touched via reflection.+-keep class com.google.mlkit.vision.text.** { *; }+-dontwarn com.google.mlkit.vision.text.**++# Tesseract4Android — JNI-bound native API, keep the whole surface.+-keep class com.googlecode.tesseract.android.** { *; }+-dontwarn com.googlecode.tesseract.android.**diff --git a/ocr-core/proguard-rules.pro b/ocr-core/proguard-rules.pronew file mode 100644index 0000000..fb164d6--- /dev/null+++ b/ocr-core/proguard-rules.pro@@ -0,0 +1 @@+# Add project specific ProGuard rules here.diff --git a/ocr-core/src/main/AndroidManifest.xml b/ocr-core/src/main/AndroidManifest.xmlnew file mode 100644index 0000000..8bdb7e1--- /dev/null+++ b/ocr-core/src/main/AndroidManifest.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++</manifest>diff --git a/ocr-core/src/main/assets/tessdata/eng.traineddata b/ocr-core/src/main/assets/tessdata/eng.traineddatanew file mode 100644index 0000000..bbef467Binary files /dev/null and b/ocr-core/src/main/assets/tessdata/eng.traineddata differdiff --git a/ocr-core/src/main/java/com/kyant/ocrcore/MlKitOcrEngine.kt b/ocr-core/src/main/java/com/kyant/ocrcore/MlKitOcrEngine.ktnew file mode 100644index 0000000..011d248--- /dev/null+++ b/ocr-core/src/main/java/com/kyant/ocrcore/MlKitOcrEngine.kt@@ -0,0 +1,51 @@+package com.kyant.ocrcore++import android.graphics.Bitmap+import com.google.mlkit.vision.common.InputImage+import com.google.mlkit.vision.text.Text+import com.google.mlkit.vision.text.TextRecognition+import com.google.mlkit.vision.text.latin.TextRecognizerOptions+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithException+import kotlinx.coroutines.suspendCancellableCoroutine++/**+ * Bundled ML Kit text recognizer (`com.google.mlkit:text-recognition`, NOT the+ * Play-Services-backed variant) — the model ships inside the APK, so recognition+ * never needs Play Services or a network call, and works even on devices without GMS.+ */+internal object MlKitOcrEngine {+ private val recognizer by lazy { TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS) }++ suspend fun recognize(bitmap: Bitmap): OcrPageResult {+ val image = InputImage.fromBitmap(bitmap, 0)+ val text = suspendCancellableCoroutine { cont ->+ recognizer.process(image)+ .addOnSuccessListener { result: Text -> cont.resume(result) }+ .addOnFailureListener { error -> cont.resumeWithException(error) }+ }++ val w = bitmap.width.toFloat().coerceAtLeast(1f)+ val h = bitmap.height.toFloat().coerceAtLeast(1f)+ val words = buildList {+ for (block in text.textBlocks) {+ for (line in block.lines) {+ for (element in line.elements) {+ val box = element.boundingBox ?: continue+ if (element.text.isEmpty()) continue+ add(+ OcrWord(+ text = element.text,+ left = (box.left / w).coerceIn(0f, 1f),+ top = (box.top / h).coerceIn(0f, 1f),+ right = (box.right / w).coerceIn(0f, 1f),+ bottom = (box.bottom / h).coerceIn(0f, 1f)+ )+ )+ }+ }+ }+ }+ return OcrPageResult(words, engineUsed = "mlkit")+ }+}diff --git a/ocr-core/src/main/java/com/kyant/ocrcore/OcrService.kt b/ocr-core/src/main/java/com/kyant/ocrcore/OcrService.ktnew file mode 100644index 0000000..f51510d--- /dev/null+++ b/ocr-core/src/main/java/com/kyant/ocrcore/OcrService.kt@@ -0,0 +1,28 @@+package com.kyant.ocrcore++import android.content.Context+import android.graphics.Bitmap++/** A single recognized word, in bitmap-normalized (0..1) coordinates. */+data class OcrWord(+ val text: String,+ val left: Float,+ val top: Float,+ val right: Float,+ val bottom: Float+)++data class OcrPageResult(+ val words: List<OcrWord>,+ val engineUsed: String+)++/**+ * Fully on-device text recognition. No implementation ever makes a network call —+ * the ML Kit model ships inside the app (not the Play-Services-downloaded variant)+ * and Tesseract's language data is bundled as an asset.+ */+interface OcrService {+ /** Recognizes text in [bitmap]. Word boxes are normalized to the bitmap's own size (0..1). */+ suspend fun recognize(context: Context, bitmap: Bitmap): OcrPageResult+}diff --git a/ocr-core/src/main/java/com/kyant/ocrcore/OcrServiceImpl.kt b/ocr-core/src/main/java/com/kyant/ocrcore/OcrServiceImpl.ktnew file mode 100644index 0000000..6826584--- /dev/null+++ b/ocr-core/src/main/java/com/kyant/ocrcore/OcrServiceImpl.kt@@ -0,0 +1,33 @@+package com.kyant.ocrcore++import android.content.Context+import android.graphics.Bitmap+import android.util.Log++/**+ * Prefers the bundled ML Kit engine (higher real-world accuracy, small footprint);+ * transparently falls back to the fully open-source Tesseract4Android engine if ML Kit+ * fails to initialize or throws during recognition (e.g. on a device whose OEM image is+ * missing pieces ML Kit's TFLite runtime needs). Both engines are 100% on-device.+ */+class OcrServiceImpl : OcrService {++ /** Sticky per-process: once ML Kit is confirmed broken on this device, stop retrying it. */+ @Volatile private var mlKitKnownBroken = false++ override suspend fun recognize(context: Context, bitmap: Bitmap): OcrPageResult {+ if (!mlKitKnownBroken) {+ runCatching { MlKitOcrEngine.recognize(bitmap) }+ .onSuccess { return it }+ .onFailure { e ->+ Log.w(TAG, "ML Kit OCR unavailable, falling back to Tesseract4Android", e)+ mlKitKnownBroken = true+ }+ }+ return TesseractOcrEngine.recognize(context, bitmap)+ }++ private companion object {+ const val TAG = "OcrService"+ }+}diff --git a/ocr-core/src/main/java/com/kyant/ocrcore/TesseractOcrEngine.kt b/ocr-core/src/main/java/com/kyant/ocrcore/TesseractOcrEngine.ktnew file mode 100644index 0000000..9bf8913--- /dev/null+++ b/ocr-core/src/main/java/com/kyant/ocrcore/TesseractOcrEngine.kt@@ -0,0 +1,76 @@+package com.kyant.ocrcore++import android.content.Context+import android.graphics.Bitmap+import com.googlecode.tesseract.android.TessBaseAPI+import com.googlecode.tesseract.android.TessBaseAPI.PageIteratorLevel+import java.io.File+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * Fully open-source (Apache-2.0) offline OCR fallback used only when the bundled+ * ML Kit engine fails to initialize or recognize (e.g. an OEM image stripped of the+ * TFLite runtime, or a non-Latin script ML Kit's default model doesn't cover).+ * Bundles `eng.traineddata` as a module asset so the fallback never needs a download.+ */+internal object TesseractOcrEngine {+ private const val LANG = "eng"++ /** Copies the bundled trained-data asset into app-private storage on first use.+ * Returns the data-path directory to pass to [TessBaseAPI.init] (the parent of "tessdata/"). */+ private fun ensureTrainedData(context: Context): File {+ val tessdataDir = File(context.filesDir, "tesseract/tessdata").apply { mkdirs() }+ val dest = File(tessdataDir, "$LANG.traineddata")+ if (!dest.exists() || dest.length() == 0L) {+ context.assets.open("tessdata/$LANG.traineddata").use { input ->+ dest.outputStream().use { output -> input.copyTo(output) }+ }+ }+ return tessdataDir.parentFile!!+ }++ suspend fun recognize(context: Context, bitmap: Bitmap): OcrPageResult = withContext(Dispatchers.Default) {+ val dataDir = ensureTrainedData(context)+ val api = TessBaseAPI()+ try {+ check(api.init(dataDir.absolutePath, LANG)) { "Tesseract init failed for $LANG" }+ api.setImage(bitmap)+ api.getUTF8Text() // triggers recognition; result consumed via the iterator below++ val w = bitmap.width.toFloat().coerceAtLeast(1f)+ val h = bitmap.height.toFloat().coerceAtLeast(1f)+ val words = buildList {+ val it = api.resultIterator+ try {+ it.begin()+ while (!it.isAtBeginningOf(PageIteratorLevel.RIL_WORD)) {+ if (!it.next(PageIteratorLevel.RIL_WORD)) return@buildList+ }+ do {+ if (it.isAtBeginningOf(PageIteratorLevel.RIL_WORD)) {+ val word = it.getUTF8Text(PageIteratorLevel.RIL_WORD)?.trim().orEmpty()+ val box = it.getBoundingRect(PageIteratorLevel.RIL_WORD)+ if (word.isNotEmpty() && box != null) {+ add(+ OcrWord(+ text = word,+ left = (box.left / w).coerceIn(0f, 1f),+ top = (box.top / h).coerceIn(0f, 1f),+ right = (box.right / w).coerceIn(0f, 1f),+ bottom = (box.bottom / h).coerceIn(0f, 1f)+ )+ )+ }+ }+ } while (it.next(PageIteratorLevel.RIL_WORD))+ } finally {+ it.delete()+ }+ }+ OcrPageResult(words, engineUsed = "tesseract")+ } finally {+ api.recycle()+ }+ }+}diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/raster/PdfRasterizer.kt b/pdf-core/src/main/java/com/kyant/pdfcore/raster/PdfRasterizer.ktindex 67c50cd..f340b42 100644--- a/pdf-core/src/main/java/com/kyant/pdfcore/raster/PdfRasterizer.kt+++ b/pdf-core/src/main/java/com/kyant/pdfcore/raster/PdfRasterizer.kt@@ -86,6 +86,31 @@ object PdfRasterizer {return results}+ /**+ * Renders a single page straight to an in-memory [Bitmap] (no file/FileProvider round-trip).+ * Used to feed on-device OCR, which only needs the pixels, not a shareable image.+ *+ * @param dpi target render density; higher improves OCR accuracy on small text at some cost+ * to speed — 200 is a reasonable OCR-quality default (vs. 150 for the export path above).+ */+ fun rasterizePageBitmap(context: Context, source: Uri, pageIndex: Int, dpi: Int = 200): Bitmap? {+ val pfd = context.contentResolver.openFileDescriptor(source, "r") ?: return null+ return pfd.use { descriptor ->+ PdfRenderer(descriptor).use { renderer ->+ if (pageIndex !in 0 until renderer.pageCount) return@use null+ renderer.openPage(pageIndex).use { page ->+ val scale = dpi / 72f+ val w = (page.width * scale).toInt().coerceAtLeast(1)+ val h = (page.height * scale).toInt().coerceAtLeast(1)+ val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ bitmap.eraseColor(Color.WHITE)+ page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)+ bitmap+ }+ }+ }+ }+/** Persist all rendered pages to the shared Pictures collection via MediaStore. */fun exportToGallery(context: Context, pages: List<RasterPage>, format: ImageFormat, albumName: String = "ClearPDF"): Int {var saved = 0diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/searchable/PdfSearchableStamper.kt b/pdf-core/src/main/java/com/kyant/pdfcore/searchable/PdfSearchableStamper.ktnew file mode 100644index 0000000..13ec844--- /dev/null+++ b/pdf-core/src/main/java/com/kyant/pdfcore/searchable/PdfSearchableStamper.kt@@ -0,0 +1,87 @@+package com.kyant.pdfcore.searchable++import android.content.Context+import android.net.Uri+import com.kyant.pdfcore.internal.PdfBox+import com.tom_roush.pdfbox.pdmodel.PDDocument+import com.tom_roush.pdfbox.pdmodel.PDPageContentStream+import com.tom_roush.pdfbox.pdmodel.font.PDType1Font+import com.tom_roush.pdfbox.pdmodel.graphics.state.RenderingMode+import com.tom_roush.pdfbox.util.Matrix++/**+ * A recognized word to stamp as invisible, searchable text. Coordinates are page-normalized+ * (0..1), top-left origin — the same convention [com.kyant.pdfcore.text.PdfTextBlock] and+ * `com.kyant.ocrcore.OcrWord` already use.+ */+data class InvisibleWord(val text: String, val left: Float, val top: Float, val right: Float, val bottom: Float)++/**+ * Bakes OCR results into a PDF as an invisible (`Tr 3`) text layer, so the output is+ * selectable/searchable/copyable in ANY PDF reader, not just ClearPDF — the same technique+ * tools like OCRmyPDF use. Pure PDFBox; the caller supplies already-recognized words (see+ * `com.kyant.ocrcore.OcrService`), so this object carries no OCR dependency of its own and+ * pdf-core stays focused on PDF I/O.+ */+object PdfSearchableStamper {++ /** The source is never modified; the result (original content + invisible text) is written to [destinationUri]. */+ fun stamp(+ context: Context,+ sourceUri: Uri,+ destinationUri: Uri,+ wordsByPage: Map<Int, List<InvisibleWord>>+ ) {+ PdfBox.ensureInitialized(context)+ val font = PDType1Font.HELVETICA++ context.contentResolver.openInputStream(sourceUri)?.use { input ->+ PDDocument.load(input).use { doc ->+ for ((pageIndex, words) in wordsByPage) {+ if (words.isEmpty() || pageIndex !in 0 until doc.numberOfPages) continue+ val page = doc.getPage(pageIndex)+ val box = page.cropBox ?: page.mediaBox ?: continue+ val w = box.width+ val h = box.height+ val originX = box.lowerLeftX+ val originY = box.lowerLeftY+ if (w <= 0f || h <= 0f) continue++ PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true).use { cs ->+ words.forEach word@{ word ->+ val sanitized = sanitize(word.text)+ if (sanitized.isBlank()) return@word+ val wordWpt = ((word.right - word.left) * w).coerceAtLeast(0.01f)+ val wordHpt = ((word.bottom - word.top) * h).coerceAtLeast(0.01f)+ val fontSize = wordHpt.coerceIn(3f, 400f)+ val rawWidth = font.getStringWidth(sanitized) / 1000f * fontSize+ // Horizontally scale the glyphs to match the OCR box's measured width, so a+ // reader's own "highlight the match" rectangle lines up with the scanned text.+ val scaleX = if (rawWidth > 0.01f) (wordWpt / rawWidth).coerceIn(0.05f, 20f) else 1f+ val x = originX + word.left * w+ // Normalized `top`/`bottom` are measured from the page's visual top; PDF+ // text-space is bottom-up, so flip and anchor at the word's baseline-ish bottom.+ val y = originY + h - word.bottom * h++ runCatching {+ cs.beginText()+ cs.setRenderingMode(RenderingMode.NEITHER)+ cs.setFont(font, fontSize)+ cs.setTextMatrix(Matrix(scaleX, 0f, 0f, 1f, x, y))+ cs.showText(sanitized)+ cs.endText()+ }+ }+ }+ }+ context.contentResolver.openOutputStream(destinationUri)?.use { output ->+ doc.save(output)+ } ?: throw IllegalStateException("Unable to write PDF")+ }+ } ?: throw IllegalStateException("Unable to read PDF")+ }++ /** PDFBox's WinAnsi encoding rejects unsupported glyphs; keep to Latin-1 (mirrors PdfWatermarker). */+ private fun sanitize(text: String): String =+ buildString { text.forEach { ch -> append(if (ch.code in 32..255) ch else ' ') } }.trim()+}diff --git a/settings.gradle.kts b/settings.gradle.ktsindex 2c0004d..15a7971 100644--- a/settings.gradle.kts+++ b/settings.gradle.kts@@ -19,10 +19,13 @@ dependencyResolutionManagement {repositories {google()mavenCentral()+ // Tesseract4Android (open-source offline OCR fallback) is published via JitPack.+ maven { url = uri("https://jitpack.io") }}}rootProject.name = "ClearPDF"include(":backdrop")include(":pdf-core")+include(":ocr-core")include(":app")