Skip to content

Open-source Android PDF and document toolkit with PDF tools, Office viewing, XLSX editing, scanning, and image editing. Built with Kotlin and Jetpack Compose.

Full PDF editor overhaul (v1.1.0)

Chethan6169a5052c6c013
diff --git a/.gitignore b/.gitignore
index 40fb0cf..0f686c8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -52,4 +52,8 @@ Thumbs.db
app/src/main/assets/adi-registration.properties
# Legacy extracted folder
-/Pdf_Tools-master/
\ No newline at end of file
+/Pdf_Tools-master/
+/ClearPDF-main/
+
+# Local Claude Code config
+.claude/
\ No newline at end of file
diff --git a/NOTICE b/NOTICE
index fa70491..cc6ace5 100644
--- a/NOTICE
+++ b/NOTICE
@@ -5,4 +5,13 @@ Source: https://github.com/Kyant0/AndroidLiquidGlass
AndroidLiquidGlass is licensed under the Apache License, Version 2.0.
+This project depends on PdfBox-Android by Tom Roush, used for lossless PDF page
+operations (merge, split, organize) and text extraction.
+Source: https://github.com/TomRoush/PdfBox-Android
+PdfBox-Android is licensed under the Apache License, Version 2.0, and is itself a
+port of Apache PDFBox (https://pdfbox.apache.org/).
+
+This project uses Google ML Kit (document scanner and on-device text recognition)
+for the scanning and text-selection features only.
+
ClearPDF remains licensed under the MIT License (see LICENSE).
diff --git a/PLAN.md b/PLAN.md
new file mode 100644
index 0000000..1bc9776
--- /dev/null
+++ b/PLAN.md
@@ -0,0 +1,106 @@
+# ClearPDF — Roadmap
+
+A living plan for turning ClearPDF into a full, Adobe-class **PDF editor** that stays
+**100% offline & privacy-first**. No cloud, no accounts, no LLM/network AI — on-device
+Google ML Kit is used **only** for the document scanner and on-device OCR text selection.
+
+Legend: ✅ done · 🚧 in progress · ⏳ planned · 💡 idea / stretch
+
+---
+
+## Phase 0 — Foundation & correctness ✅ (June 2026)
+
+- ✅ Thread-safe `PdfRenderer` engine (serialized page access — fixed crash/corruption race)
+- ✅ Page rotation + page-size APIs in the engine
+- ✅ Lossless **merge / split / extract** via PdfBox-Android (no more rasterized, blurry output)
+- ✅ Lossless **page editor** core (reorder / rotate / delete)
+- ✅ **Conversions** core: images → PDF (lossless embed), PDF → text extraction
+- ✅ Viewer **zoom/pan rewrite** — focal-point pinch, correct pan clamping, gesture layer
+ decoupled from the transform; annotations & OCR now align at any zoom
+- ✅ New Tools: **Organize Pages**, **Images → PDF**, **Extract Text**
+
+---
+
+## Phase 1 — Make the editor feel complete ⏳
+
+- ⏳ **Drag-to-reorder** pages in the Organizer (replace up/down buttons; long-press + drag)
+- ⏳ **Insert pages**: append/merge another PDF or images *into* an existing document
+- ⏳ **Duplicate page** + **add blank page** in the Organizer
+- ⏳ **Undo/redo stack** shared across annotation + page edits
+- ⏳ **Save-in-place vs Save-as-copy** choice (overwrite original when it's a writable file)
+- ⏳ **Page thumbnails strip** inside the viewer for fast navigation + jump-to-page
+- ⏳ **Continuous (vertical) scroll** reading mode in addition to paged mode
+- ⏳ Viewer **reflow guard**: remember last page & zoom per document
+
+## Phase 2 — Annotation depth (Adobe-style) ⏳
+
+- ⏳ **Text box / typewriter** tool (add real typed text, font size & color)
+- ⏳ **Signature** tool: draw once, save signatures, stamp onto pages
+- ⏳ **Sticky notes / comments** with a comments panel
+- ⏳ **Stamps** (Approved, Draft, Confidential, date stamp)
+- ⏳ **Eraser** + per-object select/move/delete (currently annotations are append-only)
+- ⏳ **Ink smoothing** for the pen (Catmull-Rom) and pressure-width if available
+- ⏳ Persist annotations as **real PDF annotations** (via PdfBox) instead of flattening only,
+ so they stay editable after save (export-flattened remains an option)
+
+## Phase 3 — Conversions & document ops ⏳
+
+- ⏳ **PDF → images** (export pages as PNG/JPG to gallery, quality + DPI options)
+- ⏳ **PDF → long image** (stitch pages into one tall PNG for sharing)
+- ⏳ **Text → PDF** screen (paste/type text, choose page size & margins — engine already supports)
+- ⏳ **Page numbers / Bates numbering** stamp
+- ⏳ **Watermark** (text or image, opacity, tiling, diagonal)
+- ⏳ **Header/footer** templates
+- ⏳ **Crop pages** (per-page or apply-to-all crop box)
+- ⏳ **Rotate-all** quick action
+
+## Phase 4 — Security & sharing ⏳
+
+- ⏳ **Password protect / encrypt** + **remove password** (PdfBox `StandardProtectionPolicy`)
+- ⏳ **Flatten** (bake annotations/forms) for safe sharing
+- ⏳ **Redaction** tool (truly remove content under a box, not just cover it)
+- ⏳ **Share sheet** integration everywhere + "Open with ClearPDF" as default PDF handler
+- ⏳ **Print** support (Android print framework)
+- ⏳ **Metadata editor** (title/author/keywords) and metadata stripping for privacy
+
+## Phase 5 — Scanning & OCR polish ⏳
+
+- ⏳ Audit/repair the scanner flow on-device (filters, multi-page, save reliability)
+- ⏳ Route scanner output through the lossless `PdfConverter` (consistent file sizes)
+- ⏳ **Searchable scans**: run ML Kit OCR over scans and embed an invisible text layer
+ (makes scanned PDFs selectable/searchable — fully on-device)
+- ⏳ In-viewer **find/search** (uses the OCR/text layer)
+- ⏳ Auto-filter suggestion per page (B&W for text, color for photos)
+
+## Phase 6 — Forms (stretch) 💡
+
+- 💡 **Fill AcroForm fields** (text, checkbox, radio, dropdown) and save
+- 💡 Detect flat forms and let users add fillable fields
+
+## Phase 7 — Library, UX & quality ⏳
+
+- ⏳ **File library / recents** with folders, rename, delete, favorites, sort & search
+- ⏳ **Bookmarks / outline** viewer (read the PDF's table of contents; add custom bookmarks)
+- ⏳ **Tablet / landscape** two-pane layout
+- ⏳ **Per-document dark mode** (invert page colors for night reading)
+- ⏳ **Haptics & motion** polish consistent with the liquid-glass language
+- ⏳ **Accessibility**: TalkBack labels, larger-text support, contrast pass
+- ⏳ **Localization** scaffolding (currently `en` only)
+
+## Phase 8 — Engineering health ⏳
+
+- ⏳ Move from `PdfServiceLocator` to a small DI setup (Hilt or manual graph)
+- ⏳ Centralize the duplicated `createOutputUri` / save logic into one repository
+- ⏳ Unit tests for `pdf-core` (merge/split/editor/converter) on JVM where possible
+- ⏳ Instrumented tests for the viewer gesture math
+- ⏳ CI (GitHub Actions): build + lint on PR
+- ⏳ Crash/ANR hardening: large-file rendering, OOM guards, RGB_565 thumbnails
+- ⏳ CONTRIBUTING.md, issue/PR templates, screenshots refresh
+
+---
+
+### Guiding principles
+1. **Offline & private** — no data leaves the device. Ever.
+2. **Lossless by default** — preserve text/vectors; only rasterize when a feature requires it.
+3. **One design language** — every new screen uses the liquid-glass components.
+4. **Editor, not just viewer** — every common Adobe action should have an offline equivalent.
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index 3a0c1e9..9af8821 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -40,8 +40,8 @@ android {
applicationId = "com.chethan616.clearpdf"
minSdk = 23
targetSdk = 36
- versionCode = 1
- versionName = "1.0.0"
+ versionCode = 2
+ versionName = "1.1.0"
androidResources.localeFilters += arrayOf("en")
}
@@ -81,7 +81,14 @@ android {
"kotlin-tooling-metadata.json",
"kotlin/**",
"META-INF/*.version",
- "META-INF/**/LICENSE.txt"
+ "META-INF/**/LICENSE.txt",
+ // PdfBox-Android bundles these and they collide with other deps.
+ "META-INF/DEPENDENCIES",
+ "META-INF/INDEX.LIST",
+ "META-INF/LICENSE",
+ "META-INF/LICENSE.md",
+ "META-INF/NOTICE",
+ "META-INF/NOTICE.md"
)
}
dex {
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.kt
index 62735d9..bdadeff 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
@@ -2,8 +2,12 @@ package com.chethan616.clearpdf.data.repository
import com.kyant.pdfcore.compressor.PdfCompressor
import com.kyant.pdfcore.compressor.PdfCompressorImpl
+import com.kyant.pdfcore.converter.PdfConverter
+import com.kyant.pdfcore.converter.PdfConverterImpl
import com.kyant.pdfcore.creator.PdfCreator
import com.kyant.pdfcore.creator.PdfCreatorImpl
+import com.kyant.pdfcore.editor.PdfEditor
+import com.kyant.pdfcore.editor.PdfEditorImpl
import com.kyant.pdfcore.merger.PdfMerger
import com.kyant.pdfcore.merger.PdfMergerImpl
import com.kyant.pdfcore.splitter.PdfSplitter
@@ -17,4 +21,6 @@ object PdfServiceLocator {
val pdfCreator: PdfCreator by lazy { PdfCreatorImpl() }
val pdfCompressor: PdfCompressor by lazy { PdfCompressorImpl() }
val pdfSplitter: PdfSplitter by lazy { PdfSplitterImpl() }
+ val pdfEditor: PdfEditor by lazy { PdfEditorImpl() }
+ val pdfConverter: PdfConverter by lazy { PdfConverterImpl() }
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/domain/usecase/OpenPdfUseCase.kt b/app/src/main/java/com/chethan616/clearpdf/domain/usecase/OpenPdfUseCase.kt
index 559d51f..440c5c2 100644
--- a/app/src/main/java/com/chethan616/clearpdf/domain/usecase/OpenPdfUseCase.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/domain/usecase/OpenPdfUseCase.kt
@@ -3,11 +3,17 @@ package com.chethan616.clearpdf.domain.usecase
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
+import android.util.Size
import com.kyant.pdfcore.model.PdfDocument
import com.kyant.pdfcore.viewer.PdfViewer
class OpenPdfUseCase(private val viewer: PdfViewer) {
fun open(context: Context, uri: Uri): PdfDocument = viewer.open(context, uri)
- fun renderPage(document: PdfDocument, pageIndex: Int, width: Int): Bitmap? = viewer.renderPage(document, pageIndex, width)
+
+ fun renderPage(document: PdfDocument, pageIndex: Int, width: Int, rotationDegrees: Int = 0): Bitmap? =
+ viewer.renderPage(document, pageIndex, width, rotationDegrees)
+
+ fun pageSize(document: PdfDocument, pageIndex: Int): Size? = viewer.pageSize(document, pageIndex)
+
fun close(document: PdfDocument) = viewer.close(document)
}
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.kt
index db7641a..1584138 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
@@ -20,8 +20,11 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import com.chethan616.clearpdf.ui.screen.CompressPdfScreen
import com.chethan616.clearpdf.ui.screen.CreatePdfScreen
+import com.chethan616.clearpdf.ui.screen.ExtractTextScreen
+import com.chethan616.clearpdf.ui.screen.ImagesToPdfScreen
import com.chethan616.clearpdf.ui.screen.HomeScreen
import com.chethan616.clearpdf.ui.screen.MergePdfScreen
+import com.chethan616.clearpdf.ui.screen.PageOrganizerScreen
import com.chethan616.clearpdf.ui.screen.PdfViewerScreen
import com.chethan616.clearpdf.ui.screen.SettingsScreen
import com.chethan616.clearpdf.ui.screen.SplitPdfScreen
@@ -29,7 +32,10 @@ import com.chethan616.clearpdf.ui.screen.ScanDocumentScreen
import com.chethan616.clearpdf.ui.screen.ToolsScreen
import com.chethan616.clearpdf.ui.viewmodel.CompressPdfViewModel
import com.chethan616.clearpdf.ui.viewmodel.CreatePdfViewModel
+import com.chethan616.clearpdf.ui.viewmodel.ExtractTextViewModel
+import com.chethan616.clearpdf.ui.viewmodel.ImagesToPdfViewModel
import com.chethan616.clearpdf.ui.viewmodel.MergePdfViewModel
+import com.chethan616.clearpdf.ui.viewmodel.PageOrganizerViewModel
import com.chethan616.clearpdf.ui.viewmodel.PdfViewerViewModel
import com.chethan616.clearpdf.ui.viewmodel.SplitPdfViewModel
import com.chethan616.clearpdf.ui.viewmodel.ScanViewModel
@@ -44,6 +50,9 @@ private const val ROUTE_MERGE = "merge_pdf"
private const val ROUTE_SPLIT = "split_pdf"
private const val ROUTE_COMPRESS = "compress_pdf"
private const val ROUTE_CREATE = "create_pdf"
+private const val ROUTE_ORGANIZE = "organize_pdf"
+private const val ROUTE_EXTRACT_TEXT = "extract_text"
+private const val ROUTE_IMAGES_TO_PDF = "images_to_pdf"
private const val ARG_PDF_URI = "uri"
private const val ROUTE_VIEWER = "$ROUTE_VIEWER_BASE?$ARG_PDF_URI={$ARG_PDF_URI}"
@@ -115,7 +124,10 @@ fun DocsNavGraph(
onNavigateToMergePdf = { navController.navigate(ROUTE_MERGE) { launchSingleTop = true } },
onNavigateToSplitPdf = { navController.navigate(ROUTE_SPLIT) { launchSingleTop = true } },
onNavigateToCompressPdf = { navController.navigate(ROUTE_COMPRESS) { launchSingleTop = true } },
- onNavigateToCreatePdf = { navController.navigate(ROUTE_CREATE) { launchSingleTop = true } }
+ onNavigateToCreatePdf = { navController.navigate(ROUTE_CREATE) { launchSingleTop = true } },
+ onNavigateToOrganizePdf = { navController.navigate(ROUTE_ORGANIZE) { launchSingleTop = true } },
+ onNavigateToExtractText = { navController.navigate(ROUTE_EXTRACT_TEXT) { launchSingleTop = true } },
+ onNavigateToImagesToPdf = { navController.navigate(ROUTE_IMAGES_TO_PDF) { launchSingleTop = true } }
)
}
@@ -234,5 +246,52 @@ fun DocsNavGraph(
onViewOutput = { uri -> navController.navigateToPdfViewer(uri) }
)
}
+
+ composable(ROUTE_ORGANIZE) {
+ val vm: PageOrganizerViewModel = viewModel(
+ factory = object : ViewModelProvider.Factory {
+ @Suppress("UNCHECKED_CAST")
+ override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T =
+ PageOrganizerViewModel(PdfServiceLocator.pdfEditor) as T
+ }
+ )
+ PageOrganizerScreen(
+ backdrop = backdrop,
+ viewModel = vm,
+ onBack = { navController.popBackStack() },
+ onViewOutput = { uri -> navController.navigateToPdfViewer(uri) }
+ )
+ }
+
+ composable(ROUTE_EXTRACT_TEXT) {
+ val vm: ExtractTextViewModel = viewModel(
+ factory = object : ViewModelProvider.Factory {
+ @Suppress("UNCHECKED_CAST")
+ override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T =
+ ExtractTextViewModel(PdfServiceLocator.pdfConverter) as T
+ }
+ )
+ ExtractTextScreen(
+ backdrop = backdrop,
+ viewModel = vm,
+ onBack = { navController.popBackStack() }
+ )
+ }
+
+ composable(ROUTE_IMAGES_TO_PDF) {
+ val vm: ImagesToPdfViewModel = viewModel(
+ factory = object : ViewModelProvider.Factory {
+ @Suppress("UNCHECKED_CAST")
+ override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T =
+ ImagesToPdfViewModel(PdfServiceLocator.pdfConverter) as T
+ }
+ )
+ ImagesToPdfScreen(
+ backdrop = backdrop,
+ viewModel = vm,
+ onBack = { navController.popBackStack() },
+ onViewOutput = { uri -> navController.navigateToPdfViewer(uri) }
+ )
+ }
}
}
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.kt
new file mode 100644
index 0000000..b690607
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ExtractTextScreen.kt
@@ -0,0 +1,125 @@
+package com.chethan616.clearpdf.ui.screen
+
+import android.content.Intent
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.text.BasicText
+import androidx.compose.foundation.text.selection.SelectionContainer
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.ArrowBackIosNew
+import androidx.compose.material.icons.rounded.ContentCopy
+import androidx.compose.material.icons.rounded.Share
+import androidx.compose.material.icons.rounded.UploadFile
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Icon
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalClipboardManager
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.chethan616.clearpdf.ui.components.LiquidButton
+import com.chethan616.clearpdf.ui.components.LiquidGlassTopBar
+import com.chethan616.clearpdf.ui.components.liquidGlassPanel
+import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
+import com.chethan616.clearpdf.ui.utils.rememberUISensor
+import com.chethan616.clearpdf.ui.viewmodel.ExtractTextViewModel
+import com.kyant.backdrop.backdrops.LayerBackdrop
+
+@Composable
+fun ExtractTextScreen(
+ backdrop: LayerBackdrop,
+ viewModel: ExtractTextViewModel,
+ onBack: () -> Unit
+) {
+ val state by viewModel.uiState.collectAsState()
+ val context = LocalContext.current
+ val clipboard = LocalClipboardManager.current
+ val uiSensor = rememberUISensor()
+ val isDark = LocalIsDarkMode.current
+ val text = if (isDark) Color(0xFFF0F0F0) else Color(0xFF222222)
+ val sub = if (isDark) Color(0xFFAAAAAA) else Color(0xFF777777)
+ val accent = Color(0xFF00838F)
+
+ val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
+ uri?.let { viewModel.onSelectFile(context, it) }
+ }
+
+ Column(
+ Modifier.fillMaxSize().statusBarsPadding().padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {
+ Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)
+ }
+ LiquidGlassTopBar("Extract Text", backdrop, uiSensor, Modifier.weight(1f), titleFontSize = 18.sp)
+ }
+
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ LiquidButton(onClick = { picker.launch(arrayOf("application/pdf")) }, backdrop = backdrop, tint = accent) {
+ Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)
+ BasicText("Pick a PDF", style = TextStyle(Color.White, 14.sp, FontWeight.Medium))
+ }
+ if (state.text.isNotEmpty()) {
+ LiquidButton(onClick = { clipboard.setText(AnnotatedString(state.text)) }, backdrop = backdrop) {
+ Icon(Icons.Rounded.ContentCopy, null, Modifier.size(16.dp), text)
+ BasicText("Copy", style = TextStyle(text, 14.sp, FontWeight.Medium))
+ }
+ LiquidButton(onClick = {
+ val send = Intent(Intent.ACTION_SEND).apply {
+ type = "text/plain"
+ putExtra(Intent.EXTRA_TEXT, state.text)
+ }
+ context.startActivity(Intent.createChooser(send, "Share text"))
+ }, backdrop = backdrop) {
+ Icon(Icons.Rounded.Share, null, Modifier.size(16.dp), text)
+ BasicText("Share", style = TextStyle(text, 14.sp, FontWeight.Medium))
+ }
+ }
+ }
+
+ state.sourceFileName.takeIf { it.isNotBlank() }?.let {
+ BasicText(it, style = TextStyle(sub, 12.sp))
+ }
+ state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFFFB300), 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.text.isNotEmpty() -> SelectionContainer(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {
+ BasicText(state.text, style = TextStyle(text, 14.sp))
+ }
+ state.hasResult -> Box(Modifier.fillMaxSize(), Alignment.Center) {
+ BasicText("No text layer in this PDF.", style = TextStyle(sub, 13.sp))
+ }
+ else -> Box(Modifier.fillMaxSize(), Alignment.Center) {
+ BasicText("Pick a PDF to pull its text.", style = TextStyle(sub, 13.sp))
+ }
+ }
+ }
+ Spacer(Modifier.height(8.dp))
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImagesToPdfScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImagesToPdfScreen.kt
new file mode 100644
index 0000000..d980783
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ImagesToPdfScreen.kt
@@ -0,0 +1,184 @@
+package com.chethan616.clearpdf.ui.screen
+
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.background
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.aspectRatio
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.lazy.grid.GridCells
+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
+import androidx.compose.foundation.lazy.grid.itemsIndexed
+import androidx.compose.foundation.shape.CircleShape
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.BasicText
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.AddPhotoAlternate
+import androidx.compose.material.icons.rounded.ArrowBackIosNew
+import androidx.compose.material.icons.rounded.Close
+import androidx.compose.material3.Icon
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import coil3.compose.AsyncImage
+import com.chethan616.clearpdf.ui.components.LiquidButton
+import com.chethan616.clearpdf.ui.components.LiquidGlassTopBar
+import com.chethan616.clearpdf.ui.components.liquidGlassPanel
+import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
+import com.chethan616.clearpdf.ui.utils.rememberUISensor
+import com.chethan616.clearpdf.ui.viewmodel.ImagesToPdfViewModel
+import com.chethan616.clearpdf.ui.components.LiquidSaveDialog
+import com.kyant.backdrop.backdrops.LayerBackdrop
+
+@Composable
+fun ImagesToPdfScreen(
+ backdrop: LayerBackdrop,
+ viewModel: ImagesToPdfViewModel,
+ onBack: () -> Unit,
+ onViewOutput: (android.net.Uri) -> Unit
+) {
+ val state by viewModel.uiState.collectAsState()
+ val context = LocalContext.current
+ val uiSensor = rememberUISensor()
+ val isDark = LocalIsDarkMode.current
+ val text = if (isDark) Color(0xFFF0F0F0) else Color(0xFF222222)
+ val sub = if (isDark) Color(0xFFAAAAAA) else Color(0xFF777777)
+ val accent = Color(0xFF5E35B1)
+
+ var showSaveDialog by remember { mutableStateOf(false) }
+
+ val picker = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { uris ->
+ viewModel.onPickImages(uris)
+ }
+
+ Column(
+ Modifier.fillMaxSize().statusBarsPadding().padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {
+ Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)
+ }
+ LiquidGlassTopBar("Images → PDF", backdrop, uiSensor, Modifier.weight(1f), titleFontSize = 18.sp)
+ }
+
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ LiquidButton(onClick = { picker.launch("image/*") }, backdrop = backdrop, tint = accent) {
+ Icon(Icons.Rounded.AddPhotoAlternate, null, Modifier.size(18.dp), Color.White)
+ BasicText("Add images", style = TextStyle(Color.White, 14.sp, FontWeight.Medium))
+ }
+ if (state.imageUris.isNotEmpty()) {
+ LiquidButton(onClick = { viewModel.clearImages() }, backdrop = backdrop) {
+ BasicText("Clear", style = TextStyle(text, 14.sp, FontWeight.Medium))
+ }
+ }
+ }
+
+ // Page-size toggle
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ LiquidButton(
+ onClick = { viewModel.setFitToA4(true) }, backdrop = backdrop,
+ surfaceColor = if (state.fitToA4) accent.copy(0.30f) else Color.White.copy(0.06f)
+ ) { BasicText("Fit to A4", style = TextStyle(text, 13.sp, FontWeight.Medium)) }
+ LiquidButton(
+ onClick = { viewModel.setFitToA4(false) }, backdrop = backdrop,
+ surfaceColor = if (!state.fitToA4) accent.copy(0.30f) else Color.White.copy(0.06f)
+ ) { BasicText("Original size", style = TextStyle(text, 13.sp, FontWeight.Medium)) }
+ }
+
+ Box(Modifier.fillMaxWidth().weight(1f)) {
+ if (state.imageUris.isEmpty()) {
+ Box(Modifier.fillMaxSize(), Alignment.Center) {
+ BasicText("Add photos to build a PDF.", style = TextStyle(sub, 13.sp))
+ }
+ } else {
+ LazyVerticalGrid(
+ columns = GridCells.Fixed(3),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier.fillMaxSize()
+ ) {
+ itemsIndexed(state.imageUris) { index, uri ->
+ Box(Modifier.aspectRatio(0.75f).clip(RoundedCornerShape(8.dp)).background(Color.White.copy(0.06f))) {
+ AsyncImage(
+ model = uri,
+ contentDescription = "Image ${index + 1}",
+ contentScale = ContentScale.Crop,
+ modifier = Modifier.fillMaxSize()
+ )
+ Box(
+ Modifier.align(Alignment.TopEnd).padding(4.dp).size(22.dp)
+ .clip(CircleShape).background(Color.Black.copy(0.55f))
+ .clickable { viewModel.removeImage(index) },
+ Alignment.Center
+ ) {
+ Icon(Icons.Rounded.Close, "Remove", Modifier.size(14.dp), Color.White)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFEF5350), 12.sp)) }
+ state.resultMessage?.let { msg ->
+ Row(Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(12.dp),
+ horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
+ BasicText(msg, style = TextStyle(Color(0xFFB9F6CA), 12.sp), modifier = Modifier.weight(1f))
+ state.lastOutputUri?.let { uri ->
+ LiquidButton(onClick = { onViewOutput(uri) }, backdrop = backdrop, tint = accent) {
+ BasicText("Open", style = TextStyle(Color.White, 12.sp, FontWeight.Medium))
+ }
+ }
+ }
+ }
+
+ LiquidButton(
+ onClick = { if (!state.isSaving && state.imageUris.isNotEmpty()) showSaveDialog = true },
+ backdrop = backdrop, tint = accent, modifier = Modifier.fillMaxWidth()
+ ) {
+ BasicText(
+ if (state.isSaving) "Creating…" else "Create PDF (${state.imageUris.size})",
+ style = TextStyle(Color.White, 15.sp, FontWeight.Medium),
+ modifier = Modifier.padding(vertical = 8.dp)
+ )
+ }
+ Spacer(Modifier.height(8.dp))
+ }
+
+ if (showSaveDialog) {
+ LiquidSaveDialog(
+ initialFileName = "ClearPDF_Images",
+ backdrop = backdrop,
+ uiSensor = uiSensor,
+ onDismiss = { showSaveDialog = false },
+ onSave = { fileName, overrideUri ->
+ showSaveDialog = false
+ viewModel.save(context, fileName, overrideUri)
+ }
+ )
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.kt
new file mode 100644
index 0000000..9f7da05
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PageOrganizerScreen.kt
@@ -0,0 +1,379 @@
+package com.chethan616.clearpdf.ui.screen
+
+import androidx.activity.compose.rememberLauncherForActivityResult
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.Image
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress
+import androidx.compose.foundation.gestures.scrollBy
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.statusBarsPadding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.foundation.lazy.rememberLazyListState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.BasicText
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.ArrowBackIosNew
+import androidx.compose.material.icons.rounded.CheckCircle
+import androidx.compose.material.icons.rounded.Delete
+import androidx.compose.material.icons.rounded.DragIndicator
+import androidx.compose.material.icons.rounded.RadioButtonUnchecked
+import androidx.compose.material.icons.rounded.RotateRight
+import androidx.compose.material.icons.rounded.UploadFile
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.Icon
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableFloatStateOf
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.alpha
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.draw.rotate
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.input.pointer.pointerInput
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.platform.LocalContext
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import androidx.compose.ui.zIndex
+import com.chethan616.clearpdf.ui.components.LiquidButton
+import com.chethan616.clearpdf.ui.components.LiquidGlassTopBar
+import com.chethan616.clearpdf.ui.components.LiquidIconButton
+import com.chethan616.clearpdf.ui.components.LiquidSaveDialog
+import com.chethan616.clearpdf.ui.components.liquidGlassPanel
+import com.chethan616.clearpdf.ui.theme.LocalIsDarkMode
+import com.chethan616.clearpdf.ui.utils.rememberUISensor
+import com.chethan616.clearpdf.ui.viewmodel.PageOrganizerViewModel
+import com.kyant.backdrop.backdrops.LayerBackdrop
+import kotlinx.coroutines.delay
+import kotlin.math.roundToInt
+
+@Composable
+fun PageOrganizerScreen(
+ backdrop: LayerBackdrop,
+ viewModel: PageOrganizerViewModel,
+ onBack: () -> Unit,
+ onViewOutput: (android.net.Uri) -> Unit
+) {
+ val state by viewModel.uiState.collectAsState()
+ val context = LocalContext.current
+ val uiSensor = rememberUISensor()
+ val isDark = LocalIsDarkMode.current
+ val text = if (isDark) Color(0xFFF0F0F0) else Color(0xFF222222)
+ val sub = if (isDark) Color(0xFFAAAAAA) else Color(0xFF777777)
+ val accent = Color(0xFF00897B)
+ val density = LocalDensity.current
+
+ var showSaveDialog by remember { mutableStateOf(false) }
+
+ // Drag-reorder state
+ val listState = rememberLazyListState()
+ var draggingIds by remember { mutableStateOf<List<Int>>(emptyList()) }
+ var pointerY by remember { mutableFloatStateOf(0f) }
+ var targetIndex by remember { mutableIntStateOf(0) }
+ var autoScroll by remember { mutableFloatStateOf(0f) }
+
+ // Continuous edge auto-scroll while dragging near top/bottom.
+ LaunchedEffect(autoScroll) {
+ if (autoScroll != 0f) {
+ while (true) { listState.scrollBy(autoScroll); delay(8) }
+ }
+ }
+
+ fun insertionIndexAtY(y: Float): Int {
+ val items = listState.layoutInfo.visibleItemsInfo
+ if (items.isEmpty()) return 0
+ for (item in items) {
+ if (y < item.offset + item.size / 2f) return item.index
+ }
+ return items.last().index + 1
+ }
+
+ val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
+ uri?.let { viewModel.onSelectFile(context, it) }
+ }
+
+ Column(
+ Modifier.fillMaxSize().statusBarsPadding().padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ LiquidButton(onClick = onBack, backdrop = backdrop, surfaceColor = Color.White.copy(0.08f)) {
+ Icon(Icons.Rounded.ArrowBackIosNew, "Back", Modifier.size(18.dp), text)
+ }
+ LiquidGlassTopBar("Organize Pages", backdrop, uiSensor, Modifier.weight(1f), titleFontSize = 18.sp)
+ }
+
+ if (state.sourceUri == null) {
+ Column(
+ Modifier.fillMaxWidth().weight(1f),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ Column(
+ Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(28.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ BasicText("Reorder, rotate & delete pages", style = TextStyle(text, 18.sp, fontWeight = FontWeight.SemiBold))
+ BasicText(
+ "Pick a PDF, drag pages to rearrange, then save a new copy. Original text & quality are preserved.",
+ style = TextStyle(sub, 13.sp)
+ )
+ LiquidButton(onClick = { picker.launch(arrayOf("application/pdf")) }, backdrop = backdrop, tint = accent) {
+ Icon(Icons.Rounded.UploadFile, null, Modifier.size(18.dp), Color.White)
+ BasicText("Pick a PDF", style = TextStyle(Color.White, 15.sp, FontWeight.Medium))
+ }
+ }
+ state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFD32F2F), 13.sp)) }
+ }
+ return@Column
+ }
+
+ if (state.isLoading) {
+ Box(Modifier.fillMaxSize(), Alignment.Center) { CircularProgressIndicator(color = accent, strokeWidth = 2.dp) }
+ return@Column
+ }
+
+ val selCount = state.selectedIds.size
+
+ // Header / selection action bar
+ Row(
+ Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(horizontal = 12.dp, vertical = 8.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ BasicText(
+ if (selCount > 0) "$selCount selected" else "${state.pages.size} pages",
+ style = TextStyle(text, 13.sp, FontWeight.SemiBold),
+ modifier = Modifier.weight(1f)
+ )
+ if (selCount > 0) {
+ LiquidButton(onClick = { viewModel.rotateSelected() }, backdrop = backdrop) {
+ Icon(Icons.Rounded.RotateRight, null, Modifier.size(16.dp), text)
+ }
+ LiquidButton(onClick = { viewModel.deleteSelected() }, backdrop = backdrop, tint = Color(0xFFEF5350)) {
+ Icon(Icons.Rounded.Delete, null, Modifier.size(16.dp), Color.White)
+ }
+ LiquidButton(onClick = { viewModel.clearSelection() }, backdrop = backdrop) {
+ BasicText("Clear", style = TextStyle(text, 12.sp, FontWeight.Medium))
+ }
+ } else {
+ LiquidButton(onClick = { viewModel.selectAll() }, backdrop = backdrop) {
+ BasicText("Select all", style = TextStyle(text, 12.sp, FontWeight.Medium))
+ }
+ }
+ }
+
+ BasicText(
+ "Long-press a page to drag · tap to select",
+ style = TextStyle(sub, 11.sp), modifier = Modifier.fillMaxWidth()
+ )
+
+ // ── Reorderable list ─────────────────────────────────────────────────────
+ Box(Modifier.fillMaxWidth().weight(1f)) {
+ LazyColumn(
+ state = listState,
+ modifier = Modifier
+ .fillMaxSize()
+ .pointerInput(Unit) {
+ detectDragGesturesAfterLongPress(
+ onDragStart = { offset ->
+ val st = viewModel.uiState.value
+ val pressed = listState.layoutInfo.visibleItemsInfo
+ .firstOrNull { offset.y.toInt() in it.offset..(it.offset + it.size) }
+ val idx = pressed?.index ?: return@detectDragGesturesAfterLongPress
+ val pressedId = st.pages.getOrNull(idx)?.originalIndex
+ ?: return@detectDragGesturesAfterLongPress
+ draggingIds = if (pressedId in st.selectedIds && st.selectedIds.size > 1)
+ st.pages.filter { it.originalIndex in st.selectedIds }.map { it.originalIndex }
+ else listOf(pressedId)
+ pointerY = offset.y
+ targetIndex = idx
+ },
+ onDrag = { change, _ ->
+ change.consume()
+ pointerY = change.position.y
+ targetIndex = insertionIndexAtY(pointerY)
+ val start = listState.layoutInfo.viewportStartOffset
+ val end = listState.layoutInfo.viewportEndOffset
+ val edge = with(density) { 72.dp.toPx() }
+ autoScroll = when {
+ pointerY < start + edge -> -14f
+ pointerY > end - edge -> 14f
+ else -> 0f
+ }
+ },
+ onDragEnd = {
+ if (draggingIds.isNotEmpty()) viewModel.movePagesTo(draggingIds, targetIndex)
+ draggingIds = emptyList(); autoScroll = 0f
+ },
+ onDragCancel = { draggingIds = emptyList(); autoScroll = 0f }
+ )
+ },
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ itemsIndexed(state.pages, key = { _, p -> p.originalIndex }) { index, page ->
+ val isSelected = page.originalIndex in state.selectedIds
+ val isDragging = page.originalIndex in draggingIds
+ Row(
+ Modifier
+ .fillMaxWidth()
+ .alpha(if (isDragging) 0.35f else 1f)
+ .liquidGlassPanel(backdrop, uiSensor)
+ .border(
+ width = if (isSelected) 2.dp else 0.dp,
+ color = if (isSelected) accent else Color.Transparent,
+ shape = RoundedCornerShape(28.dp)
+ )
+ .clickable { viewModel.toggleSelect(page.originalIndex) }
+ .padding(10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Icon(
+ if (isSelected) Icons.Rounded.CheckCircle else Icons.Rounded.RadioButtonUnchecked,
+ "Select",
+ Modifier.size(22.dp),
+ if (isSelected) accent else sub
+ )
+ Box(
+ Modifier.size(54.dp, 72.dp).clip(RoundedCornerShape(6.dp)).background(Color.White.copy(0.06f)),
+ Alignment.Center
+ ) {
+ page.thumbnail?.let { bmp ->
+ Image(
+ bitmap = bmp.asImageBitmap(),
+ contentDescription = "Page ${index + 1}",
+ contentScale = ContentScale.Fit,
+ modifier = Modifier.fillMaxSize().rotate(page.rotation.toFloat())
+ )
+ }
+ }
+ Column(Modifier.weight(1f)) {
+ BasicText("Page ${index + 1}", style = TextStyle(text, 14.sp, FontWeight.Medium))
+ BasicText(
+ "Source #${page.originalIndex + 1}" + if (page.rotation != 0) " · ${page.rotation}°" else "",
+ style = TextStyle(sub, 11.sp)
+ )
+ }
+ LiquidIconButton(onClick = { viewModel.rotatePage(index) }, backdrop = backdrop, surfaceColor = Color.White.copy(0.10f)) {
+ Icon(Icons.Rounded.RotateRight, "Rotate", Modifier.size(18.dp), text)
+ }
+ LiquidIconButton(onClick = { viewModel.deletePage(index) }, backdrop = backdrop, surfaceColor = Color(0xFFD32F2F).copy(0.18f)) {
+ Icon(Icons.Rounded.Delete, "Delete", Modifier.size(18.dp), Color(0xFFEF5350))
+ }
+ Icon(Icons.Rounded.DragIndicator, "Drag", Modifier.size(22.dp), sub)
+ }
+ }
+ }
+
+ // Insertion indicator line
+ if (draggingIds.isNotEmpty()) {
+ val info = listState.layoutInfo
+ val lineY = info.visibleItemsInfo.firstOrNull { it.index == targetIndex }?.offset?.toFloat()
+ ?: info.visibleItemsInfo.lastOrNull()?.let { (it.offset + it.size).toFloat() }
+ ?: 0f
+ Box(
+ Modifier
+ .offset { IntOffset(0, (lineY - 2f).roundToInt()) }
+ .fillMaxWidth()
+ .height(4.dp)
+ .clip(RoundedCornerShape(2.dp))
+ .background(accent)
+ .zIndex(1f)
+ )
+
+ // Floating drag preview following the finger
+ val firstId = draggingIds.first()
+ val previewPage = state.pages.firstOrNull { it.originalIndex == firstId }
+ Box(
+ Modifier
+ .offset { IntOffset(with(density) { 12.dp.toPx() }.roundToInt(), (pointerY - with(density) { 36.dp.toPx() }).roundToInt()) }
+ .zIndex(2f)
+ .clip(RoundedCornerShape(10.dp))
+ .background(accent.copy(0.92f))
+ .padding(8.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ previewPage?.thumbnail?.let { bmp ->
+ Image(
+ bitmap = bmp.asImageBitmap(),
+ contentDescription = null,
+ contentScale = ContentScale.Fit,
+ modifier = Modifier.size(36.dp, 48.dp).clip(RoundedCornerShape(4.dp)).rotate(previewPage.rotation.toFloat())
+ )
+ }
+ BasicText(
+ if (draggingIds.size > 1) "${draggingIds.size} pages" else "Move",
+ style = TextStyle(Color.White, 13.sp, FontWeight.SemiBold)
+ )
+ }
+ }
+ }
+ }
+
+ state.errorMessage?.let { BasicText(it, style = TextStyle(Color(0xFFEF5350), 12.sp)) }
+ state.resultMessage?.let { msg ->
+ Row(Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(12.dp),
+ horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
+ BasicText(msg, style = TextStyle(Color(0xFFB9F6CA), 12.sp), modifier = Modifier.weight(1f))
+ state.lastOutputUri?.let { uri ->
+ LiquidButton(onClick = { onViewOutput(uri) }, backdrop = backdrop, tint = accent) {
+ BasicText("Open", style = TextStyle(Color.White, 12.sp, FontWeight.Medium))
+ }
+ }
+ }
+ }
+
+ LiquidButton(
+ onClick = { if (!state.isSaving) showSaveDialog = true },
+ backdrop = backdrop, tint = accent, modifier = Modifier.fillMaxWidth()
+ ) {
+ BasicText(
+ if (state.isSaving) "Saving…" else "Save as new PDF",
+ style = TextStyle(Color.White, 15.sp, FontWeight.Medium),
+ modifier = Modifier.padding(vertical = 8.dp)
+ )
+ }
+ Spacer(Modifier.height(8.dp))
+ }
+
+ if (showSaveDialog) {
+ LiquidSaveDialog(
+ initialFileName = state.sourceFileName.substringBeforeLast('.').ifBlank { "Document" } + "_Organized",
+ backdrop = backdrop,
+ uiSensor = uiSensor,
+ onDismiss = { showSaveDialog = false },
+ onSave = { fileName, overrideUri ->
+ showSaveDialog = false
+ viewModel.save(context, fileName, overrideUri)
+ }
+ )
+ }
+}
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.kt
index a080620..4f586b3 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
@@ -74,6 +74,8 @@ import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.asImageBitmap
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.toArgb
@@ -185,6 +187,8 @@ fun PdfViewerScreen(
var activeTool by rememberSaveable { mutableStateOf(PdfEditTool.None) }
var currentColorLong by rememberSaveable { mutableLongStateOf(0xFF00BCD4L) }
val currentColor = Color(currentColorLong)
+ var currentStrokeWidth by rememberSaveable { mutableFloatStateOf(6f) }
+ var activeImageId by remember { mutableStateOf<Long?>(null) }
var showSaveDialog by rememberSaveable { mutableStateOf(false) }
val annotationsByPage = remember { mutableStateMapOf<Int, MutableList<PdfMarkup>>() }
@@ -194,6 +198,35 @@ fun PdfViewerScreen(
fun getPageMarks(page: Int): MutableList<PdfMarkup> =
annotationsByPage.getOrPut(page) { mutableStateListOf() }
+ // Picks an image from the device and stamps it onto the current page, centred.
+ val imagePickerLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->
+ if (uri == null) return@rememberLauncherForActivityResult
+ val bmp = runCatching {
+ context.contentResolver.openInputStream(uri)?.use {
+ android.graphics.BitmapFactory.decodeStream(it)
+ }
+ }.getOrNull() ?: return@rememberLauncherForActivityResult
+ val page = state.currentPage
+ val cs = pageCanvasSizes[page] ?: Size(bmp.width.toFloat(), bmp.height.toFloat())
+ val frame = fitBitmapRect(cs, (pageBitmapSizes[page]?.width ?: cs.width), (pageBitmapSizes[page]?.height ?: cs.height))
+ val maxW = (if (frame.width > 0f) frame.width else cs.width) * 0.5f
+ val ratio = bmp.height.toFloat() / bmp.width.toFloat().coerceAtLeast(1f)
+ val w = maxW.coerceAtLeast(1f)
+ val h = w * ratio
+ val center = if (frame.width > 0f) frame.center else Offset(cs.width / 2f, cs.height / 2f)
+ val id = System.nanoTime()
+ getPageMarks(page).add(
+ PdfMarkup.ImageMarkup(
+ id = id,
+ bitmap = bmp,
+ start = Offset(center.x - w / 2f, center.y - h / 2f),
+ end = Offset(center.x + w / 2f, center.y + h / 2f)
+ )
+ )
+ activeImageId = id
+ activeTool = PdfEditTool.Image
+ }
+
// Helper: animate zoom + pan together
suspend fun animateZoomPan(
targetZoom: Float,
@@ -328,10 +361,8 @@ fun PdfViewerScreen(
PdfEditTool.Ellipse, PdfEditTool.Line, PdfEditTool.Arrow
)
- // Pager owns swipe only at 1× zoom and no active tool
- val pagerScrollEnabled = !drawingToolActive
- && activeTool != PdfEditTool.SelectText
- && zoomScale <= 1.02f
+ // Pager owns swipe only at 1× zoom and no active editing tool
+ val pagerScrollEnabled = activeTool == PdfEditTool.None && zoomScale <= 1.02f
LaunchedEffect(pagerState.currentPage, renderWidthPx) {
viewModel.renderPage(context, pagerState.currentPage, renderWidthPx)
@@ -374,16 +405,14 @@ fun PdfViewerScreen(
pageCanvasSizes[page] = Size(sz.width.toFloat(), sz.height.toFloat())
}
) {
- // ── Zoomed content layer ──────────────────────────────────────
+ // ── Gesture layer (UNTRANSFORMED) ─────────────────────────────
+ // Gestures must live on a node that is NOT scaled by graphicsLayer,
+ // otherwise pointer deltas arrive in the zoomed coordinate space and
+ // desync from the screen-space pan/focal math. The graphicsLayer is
+ // applied to an inner wrapper around the page content instead.
Box(
modifier = Modifier
.fillMaxSize()
- .graphicsLayer(
- scaleX = zoomScale,
- scaleY = zoomScale,
- translationX = panOffset.x,
- translationY = panOffset.y
- )
// ─────────────────────────────────────────────────────
// UNIFIED GESTURE HANDLER — Adobe-style focal-point zoom
//
@@ -592,6 +621,17 @@ fun PdfViewerScreen(
)
}
) {
+ // ── Transformed content layer (zoom + pan applied here) ──────
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .graphicsLayer(
+ scaleX = zoomScale,
+ scaleY = zoomScale,
+ translationX = panOffset.x,
+ translationY = panOffset.y
+ )
+ ) {
Image(
bitmap = bitmap.asImageBitmap(),
contentDescription = "Page ${page + 1}",
@@ -620,11 +660,11 @@ fun PdfViewerScreen(
when (markup) {
is PdfMarkup.StrokeMarkup -> {
if (markup.points.size > 1) {
- val path = Path().apply {
- moveTo(markup.points.first().x, markup.points.first().y)
- markup.points.drop(1).forEach { lineTo(it.x, it.y) }
- }
- drawPath(path, markup.color.copy(markup.alpha), style = Stroke(markup.width))
+ val path = smoothPath(markup.points)
+ drawPath(
+ path, markup.color.copy(markup.alpha),
+ style = Stroke(markup.width, cap = StrokeCap.Round, join = StrokeJoin.Round)
+ )
}
}
is PdfMarkup.RectMarkup -> {
@@ -662,22 +702,45 @@ fun PdfViewerScreen(
drawLine(markup.color.copy(markup.alpha), Offset(r.left, y), Offset(r.right, y), markup.width)
}
}
+ is PdfMarkup.ImageMarkup -> {
+ val r = Rect(
+ min(markup.start.x, markup.end.x), min(markup.start.y, markup.end.y),
+ max(markup.start.x, markup.end.x), max(markup.start.y, markup.end.y)
+ )
+ drawImage(
+ image = markup.bitmap.asImageBitmap(),
+ srcOffset = androidx.compose.ui.unit.IntOffset.Zero,
+ srcSize = androidx.compose.ui.unit.IntSize(markup.bitmap.width, markup.bitmap.height),
+ dstOffset = androidx.compose.ui.unit.IntOffset(r.left.toInt(), r.top.toInt()),
+ dstSize = androidx.compose.ui.unit.IntSize(r.width.toInt().coerceAtLeast(1), r.height.toInt().coerceAtLeast(1))
+ )
+ if (activeTool == PdfEditTool.Image && markup.id == activeImageId) {
+ drawRect(Color(0xFF1976D2), r.topLeft, r.size, style = Stroke(2f))
+ // bottom-right resize handle
+ drawCircle(Color(0xFF1976D2), 14f, Offset(r.right, r.bottom))
+ drawCircle(Color.White, 7f, Offset(r.right, r.bottom))
+ }
+ }
}
}
if (draftPoints.size > 1) {
- val path = Path().apply {
- moveTo(draftPoints.first().x, draftPoints.first().y)
- draftPoints.drop(1).forEach { lineTo(it.x, it.y) }
- }
- drawPath(path, Color(0xFF00BCD4), style = Stroke(6f))
+ val path = smoothPath(draftPoints)
+ val isHl = activeTool == PdfEditTool.Highlight
+ drawPath(
+ path,
+ currentColor.copy(if (isHl) 0.32f else 0.95f),
+ style = Stroke(
+ if (isHl) currentStrokeWidth * 3.5f else currentStrokeWidth,
+ cap = StrokeCap.Round, join = StrokeJoin.Round
+ )
+ )
}
if (draftRectStart != null && draftRectEnd != null) {
val s = draftRectStart!!; val e = draftRectEnd!!
val pr = Rect(min(s.x, e.x), min(s.y, e.y), max(s.x, e.x), max(s.y, e.y))
when (activeTool) {
- PdfEditTool.Highlight -> drawRect(Color(0xFFFFEB3B).copy(0.28f), pr.topLeft, pr.size)
PdfEditTool.Rect -> drawRect(Color(0xFF42A5F5), pr.topLeft, pr.size, style = Stroke(3f))
PdfEditTool.Ellipse -> drawOval(Color(0xFF26A69A), pr.topLeft, pr.size, style = Stroke(3f))
PdfEditTool.Line -> drawLine(Color(0xFF66BB6A), s, e, 4f)
@@ -693,33 +756,42 @@ fun PdfViewerScreen(
drawRect(Color(0xFFAB47BC), r.topLeft, r.size, style = Stroke(2f))
}
}
- } // zoomed Box
+ } // transformed content layer
+ } // gesture Box
// ── Drawing overlay ───────────────────────────────────────────
if (drawingToolActive) {
Box(
Modifier.fillMaxSize().pointerInput(page, activeTool) {
+ fun toContent(o: Offset): Offset {
+ val cs = pageCanvasSizes[page] ?: Size.Zero
+ val bc = Offset(cs.width / 2f, cs.height / 2f)
+ return screenToContent(o, zoomAnim.value, Offset(panXAnim.value, panYAnim.value), bc)
+ }
+ val freehand = activeTool == PdfEditTool.Draw || activeTool == PdfEditTool.Highlight
detectDragGestures(
onDragStart = { start ->
lastInteractionAtMs = System.currentTimeMillis()
- if (activeTool == PdfEditTool.Draw) draftPoints = listOf(start)
- else { draftRectStart = start; draftRectEnd = start }
+ val p = toContent(start)
+ if (freehand) draftPoints = listOf(p)
+ else { draftRectStart = p; draftRectEnd = p }
},
onDrag = { change, _ ->
change.consume()
lastInteractionAtMs = System.currentTimeMillis()
- if (activeTool == PdfEditTool.Draw) draftPoints = draftPoints + change.position
- else draftRectEnd = change.position
+ val p = toContent(change.position)
+ if (freehand) draftPoints = draftPoints + p
+ else draftRectEnd = p
},
onDragCancel = { draftPoints = emptyList(); draftRectStart = null; draftRectEnd = null },
onDragEnd = {
when (activeTool) {
- PdfEditTool.Draw -> if (draftPoints.size > 1) marks.add(PdfMarkup.StrokeMarkup(draftPoints, currentColor, 6f, 0.95f))
- PdfEditTool.Highlight -> draftRectStart?.let { s -> draftRectEnd?.let { e -> marks.add(PdfMarkup.RectMarkup(s, e, currentColor, 0.30f, true)) } }
+ PdfEditTool.Draw -> if (draftPoints.size > 1) marks.add(PdfMarkup.StrokeMarkup(draftPoints, currentColor, currentStrokeWidth, 0.95f))
+ PdfEditTool.Highlight -> if (draftPoints.size > 1) marks.add(PdfMarkup.StrokeMarkup(draftPoints, currentColor, currentStrokeWidth * 3.5f, 0.32f))
PdfEditTool.Rect -> draftRectStart?.let { s -> draftRectEnd?.let { e -> marks.add(PdfMarkup.RectMarkup(s, e, currentColor, 1f, false)) } }
PdfEditTool.Ellipse -> draftRectStart?.let { s -> draftRectEnd?.let { e -> marks.add(PdfMarkup.OvalMarkup(s, e, currentColor, 1f, false)) } }
- PdfEditTool.Line -> draftRectStart?.let { s -> draftRectEnd?.let { e -> marks.add(PdfMarkup.LineMarkup(s, e, currentColor, 4f, 1f, false)) } }
- PdfEditTool.Arrow -> draftRectStart?.let { s -> draftRectEnd?.let { e -> marks.add(PdfMarkup.LineMarkup(s, e, currentColor, 4f, 1f, true)) } }
+ PdfEditTool.Line -> draftRectStart?.let { s -> draftRectEnd?.let { e -> marks.add(PdfMarkup.LineMarkup(s, e, currentColor, currentStrokeWidth, 1f, false)) } }
+ PdfEditTool.Arrow -> draftRectStart?.let { s -> draftRectEnd?.let { e -> marks.add(PdfMarkup.LineMarkup(s, e, currentColor, currentStrokeWidth, 1f, true)) } }
else -> Unit
}
draftPoints = emptyList(); draftRectStart = null; draftRectEnd = null
@@ -729,31 +801,113 @@ fun PdfViewerScreen(
)
}
+ // ── Eraser overlay (tap / drag to remove marks) ────────────────
+ if (activeTool == PdfEditTool.Eraser) {
+ Box(
+ Modifier.fillMaxSize().pointerInput(page) {
+ fun toContent(o: Offset): Offset {
+ val cs = pageCanvasSizes[page] ?: Size.Zero
+ val bc = Offset(cs.width / 2f, cs.height / 2f)
+ return screenToContent(o, zoomAnim.value, Offset(panXAnim.value, panYAnim.value), bc)
+ }
+ fun eraseAt(o: Offset) {
+ val p = toContent(o)
+ val idx = marks.indexOfLast { it.hitTest(p) }
+ if (idx >= 0) marks.removeAt(idx)
+ }
+ detectTapGestures { eraseAt(it); lastInteractionAtMs = System.currentTimeMillis() }
+ }.pointerInput(page) {
+ fun toContent(o: Offset): Offset {
+ val cs = pageCanvasSizes[page] ?: Size.Zero
+ val bc = Offset(cs.width / 2f, cs.height / 2f)
+ return screenToContent(o, zoomAnim.value, Offset(panXAnim.value, panYAnim.value), bc)
+ }
+ detectDragGestures(onDrag = { change, _ ->
+ change.consume()
+ val p = toContent(change.position)
+ val idx = marks.indexOfLast { it.hitTest(p) }
+ if (idx >= 0) marks.removeAt(idx)
+ lastInteractionAtMs = System.currentTimeMillis()
+ })
+ }
+ )
+ }
+
+ // ── Image move / resize overlay ────────────────────────────────
+ if (activeTool == PdfEditTool.Image && activeImageId != null) {
+ Box(
+ Modifier.fillMaxSize().pointerInput(page, activeImageId) {
+ fun toContent(o: Offset): Offset {
+ val cs = pageCanvasSizes[page] ?: Size.Zero
+ val bc = Offset(cs.width / 2f, cs.height / 2f)
+ return screenToContent(o, zoomAnim.value, Offset(panXAnim.value, panYAnim.value), bc)
+ }
+ var resizing = false
+ detectDragGestures(
+ onDragStart = { start ->
+ val p = toContent(start)
+ val idx = marks.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == activeImageId }
+ val img = marks.getOrNull(idx) as? PdfMarkup.ImageMarkup
+ resizing = img != null && (p - img.end).getDistance() <= 36f
+ lastInteractionAtMs = System.currentTimeMillis()
+ },
+ onDrag = { change, dragAmount ->
+ change.consume()
+ val idx = marks.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == activeImageId }
+ val img = marks.getOrNull(idx) as? PdfMarkup.ImageMarkup ?: return@detectDragGestures
+ val d = dragAmount / zoomAnim.value
+ marks[idx] = if (resizing) {
+ val newEnd = Offset(
+ (img.end.x + d.x).coerceAtLeast(img.start.x + 24f),
+ (img.end.y + d.y).coerceAtLeast(img.start.y + 24f)
+ )
+ img.copy(end = newEnd)
+ } else {
+ img.copy(start = img.start + d, end = img.end + d)
+ }
+ lastInteractionAtMs = System.currentTimeMillis()
+ }
+ )
+ }
+ )
+ }
+
// ── OCR selection overlay ──────────────────────────────────────
if (activeTool == PdfEditTool.SelectText) {
Box(
Modifier.fillMaxSize()
.pointerInput(page, ocrBlocks) {
+ fun toContent(o: Offset): Offset {
+ val cs = pageCanvasSizes[page] ?: Size.Zero
+ val bc = Offset(cs.width / 2f, cs.height / 2f)
+ return screenToContent(o, zoomAnim.value, Offset(panXAnim.value, panYAnim.value), bc)
+ }
detectTapGestures { tap ->
lastInteractionAtMs = System.currentTimeMillis()
val cs = pageCanvasSizes[page] ?: return@detectTapGestures
val bs = pageBitmapSizes[page] ?: return@detectTapGestures
val frame = fitBitmapRect(cs, bs.width, bs.height)
- val hit = hitTestOcrBlock(ocrBlocks, tap, frame)
+ val hit = hitTestOcrBlock(ocrBlocks, toContent(tap), frame)
if (hit != null) viewModel.toggleOcrSelection(page, hit.id)
else viewModel.clearOcrSelection(page)
}
}
.pointerInput(page, ocrBlocks) {
+ fun toContent(o: Offset): Offset {
+ val cs = pageCanvasSizes[page] ?: Size.Zero
+ val bc = Offset(cs.width / 2f, cs.height / 2f)
+ return screenToContent(o, zoomAnim.value, Offset(panXAnim.value, panYAnim.value), bc)
+ }
detectDragGesturesAfterLongPress(
onDragStart = { s ->
lastInteractionAtMs = System.currentTimeMillis()
- selDragStart = s; selDragEnd = s
+ val p = toContent(s)
+ selDragStart = p; selDragEnd = p
},
onDrag = { change, _ ->
change.consume()
lastInteractionAtMs = System.currentTimeMillis()
- selDragEnd = change.position
+ selDragEnd = toContent(change.position)
},
onDragCancel = { selDragStart = null; selDragEnd = null },
onDragEnd = {
@@ -885,10 +1039,24 @@ fun PdfViewerScreen(
)
}
- if (drawingToolActive || activeTool == PdfEditTool.SelectText) {
+ LiquidButton(
+ onClick = { imagePickerLauncher.launch("image/*") },
+ backdrop = backdrop,
+ tint = if (activeTool == PdfEditTool.Image) Color(0xFF1976D2) else Color.Transparent
+ ) { BasicText("Add Image", style = TextStyle(Color.White, 12.sp, FontWeight.Medium)) }
+
+ LiquidButton(
+ onClick = { activeTool = if (activeTool == PdfEditTool.Eraser) PdfEditTool.None else PdfEditTool.Eraser },
+ backdrop = backdrop,
+ tint = if (activeTool == PdfEditTool.Eraser) Color(0xFFEF5350) else Color.Transparent
+ ) { BasicText("Eraser", style = TextStyle(Color.White, 12.sp, FontWeight.Medium)) }
+
+ if (drawingToolActive || activeTool == PdfEditTool.SelectText ||
+ activeTool == PdfEditTool.Image || activeTool == PdfEditTool.Eraser) {
LiquidIconButton(
onClick = {
activeTool = PdfEditTool.None
+ activeImageId = null
viewModel.clearOcrSelection(state.currentPage)
},
backdrop = backdrop,
@@ -930,11 +1098,12 @@ fun PdfViewerScreen(
}
}
- // Integrated Edit Panel (Drawing or OCR)
+ // Integrated Edit Panel (Drawing / OCR / Image)
val showDrawTools = drawingToolActive
val showOcrTools = activeTool == PdfEditTool.SelectText || selectedTextCount > 0
+ val showImageTools = activeTool == PdfEditTool.Image && activeImageId != null
- AnimatedVisibility(visible = showDrawTools || showOcrTools) {
+ AnimatedVisibility(visible = showDrawTools || showOcrTools || showImageTools) {
Column(
Modifier.fillMaxWidth().liquidGlassPanel(backdrop, uiSensor).padding(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
@@ -1029,6 +1198,44 @@ fun PdfViewerScreen(
onClick = { viewModel.clearOcrSelection(state.currentPage) },
backdrop = backdrop
) { BasicText("Clear Sel", style = TextStyle(Color.White, 12.sp, FontWeight.Medium)) }
+ } else if (showImageTools) {
+ BasicText(
+ "Drag to move · drag corner to resize",
+ style = TextStyle(Color.White.copy(0.75f), 12.sp)
+ )
+ LiquidButton(
+ onClick = { imagePickerLauncher.launch("image/*") },
+ backdrop = backdrop
+ ) { BasicText("Replace", style = TextStyle(Color.White, 12.sp, FontWeight.Medium)) }
+ LiquidButton(
+ onClick = {
+ val m = getPageMarks(state.currentPage)
+ val idx = m.indexOfLast { it is PdfMarkup.ImageMarkup && it.id == activeImageId }
+ if (idx >= 0) m.removeAt(idx)
+ activeImageId = null
+ activeTool = PdfEditTool.None
+ },
+ backdrop = backdrop, tint = Color(0xFFEF5350)
+ ) { BasicText("Remove", style = TextStyle(Color.White, 12.sp, FontWeight.Medium)) }
+ }
+ }
+ }
+
+ // Thickness selector (draw tools only)
+ if (showDrawTools) {
+ Row(
+ Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ BasicText("Size", style = TextStyle(Color.White.copy(0.7f), 12.sp))
+ listOf("S" to 3f, "M" to 6f, "L" to 11f, "XL" to 18f).forEach { (label, w) ->
+ val sel = currentStrokeWidth == w
+ LiquidButton(
+ onClick = { currentStrokeWidth = w },
+ backdrop = backdrop,
+ surfaceColor = if (sel) currentColor.copy(0.30f) else Color.White.copy(0.08f)
+ ) { BasicText(label, style = TextStyle(Color.White, 12.sp, FontWeight.Medium)) }
}
}
}
@@ -1149,7 +1356,7 @@ fun PdfViewerScreen(
// Enums & sealed classes
// ─────────────────────────────────────────────────────────────────────────────
-private enum class PdfEditTool { None, Draw, Highlight, Rect, Ellipse, Line, Arrow, SelectText }
+private enum class PdfEditTool { None, Draw, Highlight, Rect, Ellipse, Line, Arrow, SelectText, Image, Eraser }
private sealed class PdfMarkup {
data class StrokeMarkup(val points: List<Offset>, val color: Color, val width: Float, val alpha: Float) : PdfMarkup()
@@ -1158,12 +1365,60 @@ private sealed class PdfMarkup {
data class LineMarkup(val start: Offset, val end: Offset, val color: Color, val width: Float, val alpha: Float, val arrowHead: Boolean) : PdfMarkup()
data class TextBlockHighlightMarkup(val blockId: String, val color: Color, val alpha: Float) : PdfMarkup()
data class TextBlockLineMarkup(val blockId: String, val color: Color, val width: Float, val alpha: Float, val strikeThrough: Boolean) : PdfMarkup()
+ data class ImageMarkup(val id: Long, val bitmap: android.graphics.Bitmap, val start: Offset, val end: Offset) : PdfMarkup()
+}
+
+/** A markup is "hittable" for the eraser if a point falls on/near it. */
+private fun PdfMarkup.hitTest(p: Offset): Boolean = when (this) {
+ is PdfMarkup.StrokeMarkup -> points.any { (it - p).getDistance() <= (width / 2f + 14f) }
+ is PdfMarkup.RectMarkup -> nearRectEdgeOrInside(p, start, end, filled)
+ is PdfMarkup.OvalMarkup -> nearRectEdgeOrInside(p, start, end, filled)
+ is PdfMarkup.LineMarkup -> distanceToSegment(p, start, end) <= (width / 2f + 14f)
+ is PdfMarkup.ImageMarkup -> {
+ val r = Rect(min(start.x, end.x), min(start.y, end.y), max(start.x, end.x), max(start.y, end.y))
+ p.x in r.left..r.right && p.y in r.top..r.bottom
+ }
+ else -> false
+}
+
+private fun nearRectEdgeOrInside(p: Offset, a: Offset, b: Offset, filled: Boolean): Boolean {
+ val r = Rect(min(a.x, b.x), min(a.y, b.y), max(a.x, b.x), max(a.y, b.y))
+ if (filled) return p.x in r.left..r.right && p.y in r.top..r.bottom
+ val pad = 14f
+ val inOuter = p.x in (r.left - pad)..(r.right + pad) && p.y in (r.top - pad)..(r.bottom + pad)
+ val inInner = p.x in (r.left + pad)..(r.right - pad) && p.y in (r.top + pad)..(r.bottom - pad)
+ return inOuter && !inInner
+}
+
+private fun distanceToSegment(p: Offset, a: Offset, b: Offset): Float {
+ val ab = b - a
+ val lenSq = ab.x * ab.x + ab.y * ab.y
+ if (lenSq <= 0.0001f) return (p - a).getDistance()
+ val t = (((p.x - a.x) * ab.x + (p.y - a.y) * ab.y) / lenSq).coerceIn(0f, 1f)
+ return (p - Offset(a.x + ab.x * t, a.y + ab.y * t)).getDistance()
}
// ─────────────────────────────────────────────────────────────────────────────
// Geometry helpers
// ─────────────────────────────────────────────────────────────────────────────
+/** Builds a smooth path from raw points using quadratic midpoint smoothing. */
+private fun smoothPath(points: List<Offset>): Path {
+ val path = Path()
+ if (points.isEmpty()) return path
+ path.moveTo(points.first().x, points.first().y)
+ if (points.size < 3) {
+ points.drop(1).forEach { path.lineTo(it.x, it.y) }
+ return path
+ }
+ for (i in 1 until points.size - 1) {
+ val mid = Offset((points[i].x + points[i + 1].x) / 2f, (points[i].y + points[i + 1].y) / 2f)
+ path.quadraticTo(points[i].x, points[i].y, mid.x, mid.y)
+ }
+ path.lineTo(points.last().x, points.last().y)
+ return path
+}
+
private fun fitBitmapRect(container: Size, bitmapWidth: Float, bitmapHeight: Float): Rect {
if (bitmapWidth <= 0f || bitmapHeight <= 0f || container.width <= 0f || container.height <= 0f)
return Rect.Zero
@@ -1269,6 +1524,12 @@ private fun buildExportOverlays(
))
}
}
+ is PdfMarkup.ImageMarkup -> {
+ val s = screenToNormalized(markup.start, ir)
+ val e = screenToNormalized(markup.end, ir)
+ if (s != null && e != null)
+ overlays.add(ExportOverlay.ImageStamp(markup.bitmap, s, e))
+ }
}
}
if (overlays.isNotEmpty()) output[page] = overlays
@@ -1276,6 +1537,19 @@ private fun buildExportOverlays(
return output
}
+/**
+ * Maps a screen-space pointer position into the un-zoomed content coordinate space.
+ *
+ * The content layer is transformed by graphicsLayer as:
+ * screen = (P - center) * scale + center + pan
+ * so the inverse used here is:
+ * P = (screen - center - pan) / scale + center
+ *
+ * This keeps annotations/OCR hit-testing aligned with the page at any zoom level.
+ */
+private fun screenToContent(screen: Offset, scale: Float, pan: Offset, center: Offset): Offset =
+ if (scale <= 0f) screen else (screen - center - pan) / scale + center
+
private fun screenToNormalized(point: Offset, imageRect: Rect): NormalizedPoint? {
if (imageRect.width <= 0f || imageRect.height <= 0f) return null
return NormalizedPoint(
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ToolsScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ToolsScreen.kt
index aeb2f09..71848b6 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/ToolsScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/ToolsScreen.kt
@@ -19,6 +19,9 @@ import androidx.compose.material.icons.automirrored.rounded.CallMerge
import androidx.compose.material.icons.automirrored.rounded.CallSplit
import androidx.compose.material.icons.rounded.Compress
import androidx.compose.material.icons.rounded.FileOpen
+import androidx.compose.material.icons.rounded.Image
+import androidx.compose.material.icons.rounded.Reorder
+import androidx.compose.material.icons.rounded.TextSnippet
import androidx.compose.material.icons.automirrored.rounded.NoteAdd
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
@@ -41,7 +44,10 @@ fun ToolsScreen(
onNavigateToMergePdf: () -> Unit,
onNavigateToSplitPdf: () -> Unit,
onNavigateToCompressPdf: () -> Unit,
- onNavigateToCreatePdf: () -> Unit
+ onNavigateToCreatePdf: () -> Unit,
+ onNavigateToOrganizePdf: () -> Unit = {},
+ onNavigateToExtractText: () -> Unit = {},
+ onNavigateToImagesToPdf: () -> Unit = {}
) {
val isDarkMode = LocalIsDarkMode.current
val isLight = !isDarkMode
@@ -98,12 +104,38 @@ fun ToolsScreen(
}
}
- LiquidGlassCard(
- title = "Create PDF", subtitle = "From scratch, images, or text",
- accentColor = Color(0xFFE65100), backdrop = backdrop, uiSensor = uiSensor,
- onClick = onNavigateToCreatePdf, modifier = Modifier.fillMaxWidth()
- ) {
- Icon(Icons.AutoMirrored.Rounded.NoteAdd, null, Modifier.size(26.dp), Color(0xFFE65100))
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ LiquidGlassCard(
+ title = "Organize", subtitle = "Reorder & rotate",
+ accentColor = Color(0xFF00897B), backdrop = backdrop, uiSensor = uiSensor,
+ onClick = onNavigateToOrganizePdf, modifier = Modifier.weight(1f)
+ ) {
+ Icon(Icons.Rounded.Reorder, null, Modifier.size(26.dp), Color(0xFF00897B))
+ }
+ LiquidGlassCard(
+ title = "Images → PDF", subtitle = "Photos to PDF",
+ accentColor = Color(0xFF5E35B1), backdrop = backdrop, uiSensor = uiSensor,
+ onClick = onNavigateToImagesToPdf, modifier = Modifier.weight(1f)
+ ) {
+ Icon(Icons.Rounded.Image, null, Modifier.size(26.dp), Color(0xFF5E35B1))
+ }
+ }
+
+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ LiquidGlassCard(
+ title = "Extract Text", subtitle = "Copy text out",
+ accentColor = Color(0xFF00838F), backdrop = backdrop, uiSensor = uiSensor,
+ onClick = onNavigateToExtractText, modifier = Modifier.weight(1f)
+ ) {
+ Icon(Icons.Rounded.TextSnippet, null, Modifier.size(26.dp), Color(0xFF00838F))
+ }
+ LiquidGlassCard(
+ title = "Create PDF", subtitle = "Blank, images, text",
+ accentColor = Color(0xFFE65100), backdrop = backdrop, uiSensor = uiSensor,
+ onClick = onNavigateToCreatePdf, modifier = Modifier.weight(1f)
+ ) {
+ Icon(Icons.AutoMirrored.Rounded.NoteAdd, null, Modifier.size(26.dp), Color(0xFFE65100))
+ }
}
Spacer(Modifier.height(80.dp))
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.kt
new file mode 100644
index 0000000..ec0f321
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ExtractTextViewModel.kt
@@ -0,0 +1,66 @@
+package com.chethan616.clearpdf.ui.viewmodel
+
+import android.content.Context
+import android.content.Intent
+import android.net.Uri
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.kyant.pdfcore.converter.PdfConverter
+import com.kyant.pdfcore.model.PdfDocument
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+data class ExtractTextUiState(
+ val sourceFileName: String = "",
+ val isExtracting: Boolean = false,
+ val text: String = "",
+ val hasResult: Boolean = false,
+ val errorMessage: String? = null
+)
+
+class ExtractTextViewModel(private val converter: PdfConverter) : ViewModel() {
+ private val _uiState = MutableStateFlow(ExtractTextUiState())
+ val uiState: StateFlow<ExtractTextUiState> = _uiState.asStateFlow()
+
+ fun onSelectFile(context: Context, uri: Uri) {
+ _uiState.value = ExtractTextUiState(isExtracting = true)
+ viewModelScope.launch {
+ try {
+ runCatching {
+ context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION)
+ }
+ val name = queryFileName(context, uri) ?: "Unknown.pdf"
+ val source = PdfDocument(uri = uri, name = name)
+ val extracted = withContext(Dispatchers.IO) { converter.extractText(context, source) }.trim()
+ _uiState.value = ExtractTextUiState(
+ sourceFileName = name,
+ isExtracting = false,
+ text = extracted,
+ hasResult = true,
+ errorMessage = if (extracted.isEmpty())
+ "No selectable text found. This PDF may be a scan/image — try the scanner's OCR instead."
+ else null
+ )
+ } catch (e: Exception) {
+ _uiState.value = ExtractTextUiState(isExtracting = false, errorMessage = e.message ?: "Extraction failed")
+ }
+ }
+ }
+
+ fun reset() {
+ _uiState.value = ExtractTextUiState()
+ }
+
+ private fun queryFileName(context: Context, uri: Uri): String? = try {
+ context.contentResolver.query(uri, null, null, null, null)?.use { c ->
+ if (c.moveToFirst()) {
+ val idx = c.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
+ if (idx >= 0) c.getString(idx) else null
+ } else null
+ }
+ } catch (_: Exception) { null }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ImagesToPdfViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ImagesToPdfViewModel.kt
new file mode 100644
index 0000000..a8766d5
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/ImagesToPdfViewModel.kt
@@ -0,0 +1,124 @@
+package com.chethan616.clearpdf.ui.viewmodel
+
+import android.content.ContentValues
+import android.content.Context
+import android.net.Uri
+import android.os.Build
+import android.os.Environment
+import android.provider.MediaStore
+import androidx.core.content.FileProvider
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.chethan616.clearpdf.data.repository.GitHubStarPromptManager
+import com.chethan616.clearpdf.data.repository.RecentFile
+import com.chethan616.clearpdf.data.repository.RecentFilesManager
+import com.chethan616.clearpdf.data.repository.SaveLocationManager
+import com.chethan616.clearpdf.ui.utils.StarPromptEventBus
+import com.kyant.pdfcore.converter.PdfConverter
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+data class ImagesToPdfUiState(
+ val imageUris: List<Uri> = emptyList(),
+ val fitToA4: Boolean = true,
+ val isSaving: Boolean = false,
+ val resultMessage: String? = null,
+ val errorMessage: String? = null,
+ val lastOutputUri: Uri? = null,
+ val saveLocationLabel: String = "Downloads (default)"
+)
+
+class ImagesToPdfViewModel(private val converter: PdfConverter) : ViewModel() {
+ private val _uiState = MutableStateFlow(ImagesToPdfUiState())
+ val uiState: StateFlow<ImagesToPdfUiState> = _uiState.asStateFlow()
+
+ fun onPickImages(uris: List<Uri>) {
+ if (uris.isEmpty()) return
+ _uiState.value = _uiState.value.copy(
+ imageUris = _uiState.value.imageUris + uris,
+ resultMessage = null,
+ errorMessage = null
+ )
+ }
+
+ fun removeImage(index: Int) {
+ val list = _uiState.value.imageUris.toMutableList()
+ if (index in list.indices) list.removeAt(index)
+ _uiState.value = _uiState.value.copy(imageUris = list)
+ }
+
+ fun clearImages() {
+ _uiState.value = _uiState.value.copy(imageUris = emptyList(), resultMessage = null, errorMessage = null)
+ }
+
+ fun setFitToA4(fit: Boolean) {
+ _uiState.value = _uiState.value.copy(fitToA4 = fit)
+ }
+
+ fun save(context: Context, fileName: String, overrideUri: Uri? = null) {
+ val images = _uiState.value.imageUris
+ if (images.isEmpty()) {
+ _uiState.value = _uiState.value.copy(errorMessage = "Add at least one image")
+ return
+ }
+ _uiState.value = _uiState.value.copy(isSaving = true, errorMessage = null, resultMessage = null, lastOutputUri = null)
+ viewModelScope.launch {
+ try {
+ val target = if (fileName.endsWith(".pdf", true)) fileName else "$fileName.pdf"
+ val saveLabel = SaveLocationManager.getSavePathDisplay(context)
+ val outUri = withContext(Dispatchers.IO) { createOutputUri(context, target, overrideUri) }
+ withContext(Dispatchers.IO) {
+ converter.imagesToPdf(context, images, outUri, fitToA4 = _uiState.value.fitToA4)
+ }
+ RecentFilesManager.addRecent(context, RecentFile(
+ name = target,
+ uriString = outUri.toString(),
+ timestamp = System.currentTimeMillis(),
+ pageCount = images.size
+ ))
+ _uiState.value = _uiState.value.copy(
+ isSaving = false,
+ lastOutputUri = outUri,
+ saveLocationLabel = saveLabel,
+ resultMessage = "Created ${images.size}-page PDF\nSaved to $saveLabel"
+ )
+ if (GitHubStarPromptManager.recordPdfInteraction(context)) StarPromptEventBus.requestPrompt()
+ } catch (e: Exception) {
+ _uiState.value = _uiState.value.copy(isSaving = false, errorMessage = e.message ?: "Conversion failed")
+ }
+ }
+ }
+
+ fun clearFeedback() {
+ _uiState.value = _uiState.value.copy(resultMessage = null, errorMessage = null)
+ }
+
+ private fun createOutputUri(context: Context, fileName: String, overrideUri: Uri?): Uri {
+ val customUri = overrideUri ?: SaveLocationManager.getSaveUri(context)
+ if (customUri != null) {
+ runCatching {
+ androidx.documentfile.provider.DocumentFile.fromTreeUri(context, customUri)
+ ?.createFile("application/pdf", fileName)?.uri
+ }.getOrNull()?.let { return it }
+ }
+ 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/PageOrganizerViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.kt
new file mode 100644
index 0000000..597e7f1
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PageOrganizerViewModel.kt
@@ -0,0 +1,247 @@
+package com.chethan616.clearpdf.ui.viewmodel
+
+import android.content.ContentValues
+import android.content.Context
+import android.content.Intent
+import android.graphics.Bitmap
+import android.net.Uri
+import android.os.Build
+import android.os.Environment
+import android.provider.MediaStore
+import androidx.core.content.FileProvider
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.chethan616.clearpdf.data.repository.GitHubStarPromptManager
+import com.chethan616.clearpdf.data.repository.RecentFile
+import com.chethan616.clearpdf.data.repository.RecentFilesManager
+import com.chethan616.clearpdf.data.repository.SaveLocationManager
+import com.chethan616.clearpdf.ui.utils.StarPromptEventBus
+import com.kyant.pdfcore.editor.PdfEditor
+import com.kyant.pdfcore.model.PdfDocument
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+/**
+ * One page in the organiser: which source page it came from, the extra rotation the
+ * user applied, and a cached thumbnail.
+ */
+data class OrganizerPage(
+ val originalIndex: Int,
+ val rotation: Int = 0,
+ val thumbnail: Bitmap? = null
+)
+
+data class PageOrganizerUiState(
+ val sourceFileName: String = "",
+ val sourceUri: Uri? = null,
+ val pages: List<OrganizerPage> = emptyList(),
+ /** Stable ids (= originalIndex) of currently multi-selected pages. */
+ val selectedIds: Set<Int> = emptySet(),
+ val isLoading: Boolean = false,
+ val isSaving: Boolean = false,
+ val resultMessage: String? = null,
+ val errorMessage: String? = null,
+ val lastOutputUri: Uri? = null,
+ val saveLocationLabel: String = "Downloads (default)"
+)
+
+class PageOrganizerViewModel(private val editor: PdfEditor) : ViewModel() {
+ private val _uiState = MutableStateFlow(PageOrganizerUiState())
+ val uiState: StateFlow<PageOrganizerUiState> = _uiState.asStateFlow()
+
+ fun onSelectFile(context: Context, uri: Uri) {
+ _uiState.value = PageOrganizerUiState(isLoading = true)
+ viewModelScope.launch {
+ try {
+ runCatching {
+ context.contentResolver.takePersistableUriPermission(
+ uri, Intent.FLAG_GRANT_READ_URI_PERMISSION
+ )
+ }
+ val name = queryFileName(context, uri) ?: "Unknown.pdf"
+ val pages = withContext(Dispatchers.IO) { renderThumbnails(context, uri) }
+ _uiState.value = PageOrganizerUiState(
+ sourceFileName = name,
+ sourceUri = uri,
+ pages = pages.mapIndexed { i, bmp -> OrganizerPage(originalIndex = i, thumbnail = bmp) }
+ )
+ } catch (e: Exception) {
+ _uiState.value = PageOrganizerUiState(errorMessage = e.message ?: "Could not open PDF")
+ }
+ }
+ }
+
+ fun rotatePage(index: Int, deltaDegrees: Int = 90) {
+ val pages = _uiState.value.pages.toMutableList()
+ if (index !in pages.indices) return
+ val current = pages[index]
+ pages[index] = current.copy(rotation = (((current.rotation + deltaDegrees) % 360) + 360) % 360)
+ _uiState.value = _uiState.value.copy(pages = pages, resultMessage = null)
+ }
+
+ fun deletePage(index: Int) {
+ val pages = _uiState.value.pages.toMutableList()
+ if (index !in pages.indices || pages.size <= 1) return
+ val removed = pages.removeAt(index)
+ _uiState.value = _uiState.value.copy(
+ pages = pages,
+ selectedIds = _uiState.value.selectedIds - removed.originalIndex,
+ resultMessage = null
+ )
+ }
+
+ // ── Selection ─────────────────────────────────────────────────────────────
+
+ fun toggleSelect(id: Int) {
+ val sel = _uiState.value.selectedIds.toMutableSet()
+ if (!sel.add(id)) sel.remove(id)
+ _uiState.value = _uiState.value.copy(selectedIds = sel, resultMessage = null)
+ }
+
+ fun clearSelection() {
+ _uiState.value = _uiState.value.copy(selectedIds = emptySet())
+ }
+
+ fun selectAll() {
+ _uiState.value = _uiState.value.copy(selectedIds = _uiState.value.pages.map { it.originalIndex }.toSet())
+ }
+
+ fun rotateSelected(deltaDegrees: Int = 90) {
+ val sel = _uiState.value.selectedIds
+ if (sel.isEmpty()) return
+ val pages = _uiState.value.pages.map {
+ if (it.originalIndex in sel) it.copy(rotation = (((it.rotation + deltaDegrees) % 360) + 360) % 360) else it
+ }
+ _uiState.value = _uiState.value.copy(pages = pages, resultMessage = null)
+ }
+
+ fun deleteSelected() {
+ val sel = _uiState.value.selectedIds
+ if (sel.isEmpty()) return
+ val pages = _uiState.value.pages.filterNot { it.originalIndex in sel }
+ if (pages.isEmpty()) {
+ _uiState.value = _uiState.value.copy(errorMessage = "Can't delete every page")
+ return
+ }
+ _uiState.value = _uiState.value.copy(pages = pages, selectedIds = emptySet(), resultMessage = null)
+ }
+
+ // ── Drag reorder ────────────────────────────────────────────────────────────
+
+ /**
+ * Moves the pages identified by [ids] (kept in their current relative order) so they
+ * land at [targetIndex] in the full list. Powers both single- and multi-page drag.
+ */
+ fun movePagesTo(ids: List<Int>, targetIndex: Int) {
+ if (ids.isEmpty()) return
+ val current = _uiState.value.pages
+ val idSet = ids.toSet()
+ val moving = current.filter { it.originalIndex in idSet }
+ if (moving.isEmpty()) return
+ val remaining = current.filterNot { it.originalIndex in idSet }
+ val removedBefore = current.take(targetIndex.coerceIn(0, current.size)).count { it.originalIndex in idSet }
+ val insertAt = (targetIndex - removedBefore).coerceIn(0, remaining.size)
+ val result = remaining.toMutableList().apply { addAll(insertAt, moving) }
+ _uiState.value = _uiState.value.copy(pages = result, resultMessage = null)
+ }
+
+ fun save(context: Context, fileName: String, overrideUri: Uri? = null) {
+ val src = _uiState.value.sourceUri ?: return
+ val pages = _uiState.value.pages
+ if (pages.isEmpty()) return
+ _uiState.value = _uiState.value.copy(isSaving = true, errorMessage = null, resultMessage = null, lastOutputUri = null)
+ viewModelScope.launch {
+ try {
+ val target = if (fileName.endsWith(".pdf", true)) fileName else "$fileName.pdf"
+ val saveLabel = SaveLocationManager.getSavePathDisplay(context)
+ val outUri = withContext(Dispatchers.IO) { createOutputUri(context, target, overrideUri) }
+ val source = PdfDocument(uri = src, name = _uiState.value.sourceFileName)
+ val order = pages.map { it.originalIndex }
+ val rotations = pages.associate { it.originalIndex to it.rotation }.filterValues { it != 0 }
+ withContext(Dispatchers.IO) { editor.applyPageEdits(context, source, order, rotations, outUri) }
+
+ RecentFilesManager.addRecent(context, RecentFile(
+ name = queryFileName(context, outUri) ?: target,
+ uriString = outUri.toString(),
+ timestamp = System.currentTimeMillis(),
+ pageCount = pages.size
+ ))
+ _uiState.value = _uiState.value.copy(
+ isSaving = false,
+ lastOutputUri = outUri,
+ saveLocationLabel = saveLabel,
+ resultMessage = "Saved ${pages.size} pages\nSaved to $saveLabel"
+ )
+ if (GitHubStarPromptManager.recordPdfInteraction(context)) StarPromptEventBus.requestPrompt()
+ } catch (e: Exception) {
+ _uiState.value = _uiState.value.copy(isSaving = false, errorMessage = e.message ?: "Save failed")
+ }
+ }
+ }
+
+ fun clearFeedback() {
+ _uiState.value = _uiState.value.copy(resultMessage = null, errorMessage = null)
+ }
+
+ private fun renderThumbnails(context: Context, uri: Uri): List<Bitmap?> {
+ val fd = context.contentResolver.openFileDescriptor(uri, "r") ?: return emptyList()
+ return fd.use {
+ val renderer = android.graphics.pdf.PdfRenderer(it)
+ try {
+ (0 until renderer.pageCount).map { i ->
+ runCatching {
+ val page = renderer.openPage(i)
+ val thumbWidth = 300
+ val scale = thumbWidth.toFloat() / page.width
+ val thumbHeight = (page.height * scale).toInt().coerceAtLeast(1)
+ val bmp = Bitmap.createBitmap(thumbWidth, thumbHeight, Bitmap.Config.ARGB_8888)
+ bmp.eraseColor(android.graphics.Color.WHITE)
+ page.render(bmp, null, null, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
+ page.close()
+ bmp
+ }.getOrNull()
+ }
+ } finally {
+ renderer.close()
+ }
+ }
+ }
+
+ private fun queryFileName(context: Context, uri: Uri): String? = try {
+ context.contentResolver.query(uri, null, null, null, null)?.use { c ->
+ if (c.moveToFirst()) {
+ val idx = c.getColumnIndex(android.provider.OpenableColumns.DISPLAY_NAME)
+ if (idx >= 0) c.getString(idx) else null
+ } else null
+ }
+ } catch (_: Exception) { null }
+
+ private fun createOutputUri(context: Context, fileName: String, overrideUri: Uri?): Uri {
+ val customUri = overrideUri ?: SaveLocationManager.getSaveUri(context)
+ if (customUri != null) {
+ runCatching {
+ val docUri = androidx.documentfile.provider.DocumentFile.fromTreeUri(context, customUri)
+ docUri?.createFile("application/pdf", fileName)?.uri
+ }.getOrNull()?.let { return it }
+ }
+ 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/PdfViewerViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/PdfViewerViewModel.kt
index 6a0f51c..45149dd 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
@@ -107,6 +107,12 @@ sealed class ExportOverlay {
val alpha: Float,
val arrowHead: Boolean
) : ExportOverlay()
+
+ data class ImageStamp(
+ val bitmap: Bitmap,
+ val start: NormalizedPoint,
+ val end: NormalizedPoint
+ ) : ExportOverlay()
}
class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel() {
@@ -628,6 +634,16 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
canvas.drawLine(endX, endY, x2, y2, paint)
}
}
+
+ is ExportOverlay.ImageStamp -> {
+ val dst = normalizedRect(
+ overlay.start.x, overlay.start.y, overlay.end.x, overlay.end.y, width, height
+ )
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { isFilterBitmap = true }
+ if (!overlay.bitmap.isRecycled) {
+ canvas.drawBitmap(overlay.bitmap, null, dst, paint)
+ }
+ }
}
}
}
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index efba48b..5f9d24d 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -16,6 +16,7 @@ mlkitTextRecognition = "16.0.1"
camerax = "1.4.1"
coil = "3.0.4"
accompanist = "0.36.0"
+pdfbox = "2.0.27.0"
[libraries]
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "serialization" }
@@ -28,6 +29,7 @@ androidx-compose-material-ripple = { group = "androidx.compose.material", name =
androidx-compose-material3 = { group = "androidx.compose.material3", name = "material3", version.ref = "material3" }
androidx-compose-material-icons-extended = { group = "androidx.compose.material", name = "material-icons-extended", version.ref = "materialIconsExtended" }
kyant-shapes = { group = "io.github.kyant0", name = "shapes", version.ref = "kyantShapes" }
+pdfbox-android = { group = "com.tom-roush", name = "pdfbox-android", version.ref = "pdfbox" }
androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigation" }
androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" }
androidx-lifecycle-runtime-compose = { group = "androidx.lifecycle", name = "lifecycle-runtime-compose", version.ref = "lifecycle" }
diff --git a/pdf-core/build.gradle.kts b/pdf-core/build.gradle.kts
index 90a16c1..f56fe61 100644
--- a/pdf-core/build.gradle.kts
+++ b/pdf-core/build.gradle.kts
@@ -28,4 +28,8 @@ kotlin {
dependencies {
implementation(libs.androidx.core.ktx)
+
+ // Lossless PDF page operations (merge / split / reorder / rotate / text extraction).
+ // PdfRenderer can only rasterise pages; PdfBox preserves the original text & vectors.
+ implementation(libs.pdfbox.android)
}
diff --git a/pdf-core/consumer-rules.pro b/pdf-core/consumer-rules.pro
index e69de29..703917f 100644
--- a/pdf-core/consumer-rules.pro
+++ b/pdf-core/consumer-rules.pro
@@ -0,0 +1,8 @@
+# PdfBox-Android (Tom Roush) — keep classes touched via reflection / resource loading.
+-keep class com.tom_roush.pdfbox.** { *; }
+-keep class com.tom_roush.fontbox.** { *; }
+-keep class com.tom_roush.harmony.** { *; }
+-dontwarn com.tom_roush.pdfbox.**
+-dontwarn com.tom_roush.fontbox.**
+-dontwarn org.apache.**
+-dontwarn javax.**
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/converter/PdfConverter.kt b/pdf-core/src/main/java/com/kyant/pdfcore/converter/PdfConverter.kt
new file mode 100644
index 0000000..387edd8
--- /dev/null
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/converter/PdfConverter.kt
@@ -0,0 +1,112 @@
+package com.kyant.pdfcore.converter
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.net.Uri
+import com.kyant.pdfcore.internal.PdfBox
+import com.kyant.pdfcore.model.PdfDocument
+import com.tom_roush.pdfbox.pdmodel.PDDocument
+import com.tom_roush.pdfbox.pdmodel.PDPage
+import com.tom_roush.pdfbox.pdmodel.PDPageContentStream
+import com.tom_roush.pdfbox.pdmodel.common.PDRectangle
+import com.tom_roush.pdfbox.pdmodel.graphics.image.JPEGFactory
+import com.tom_roush.pdfbox.text.PDFTextStripper
+
+/**
+ * Conversions between PDF and other formats.
+ */
+interface PdfConverter {
+
+ /**
+ * Build a PDF from a list of image [imageUris], one image per page.
+ *
+ * @param fitToA4 when true each page is A4 and the image is centred/scaled to fit;
+ * when false each page matches its image's pixel dimensions.
+ * @param jpegQuality 0..100 quality for the embedded JPEGs.
+ */
+ fun imagesToPdf(
+ context: Context,
+ imageUris: List<Uri>,
+ outputUri: Uri,
+ fitToA4: Boolean = true,
+ jpegQuality: Int = 85
+ ): PdfDocument
+
+ /** Extract all text from [source] (empty string for scanned/imaged PDFs without a text layer). */
+ fun extractText(context: Context, source: PdfDocument): String
+}
+
+class PdfConverterImpl : PdfConverter {
+
+ override fun imagesToPdf(
+ context: Context,
+ imageUris: List<Uri>,
+ outputUri: Uri,
+ fitToA4: Boolean,
+ jpegQuality: Int
+ ): PdfDocument {
+ PdfBox.ensureInitialized(context)
+ if (imageUris.isEmpty()) throw IllegalArgumentException("No images to convert")
+
+ val doc = PDDocument()
+ var pages = 0
+ try {
+ for (uri in imageUris) {
+ val bitmap = decodeBitmap(context, uri) ?: continue
+ try {
+ val pdImage = JPEGFactory.createFromImage(doc, bitmap, jpegQuality / 100f)
+ val page = if (fitToA4) {
+ PDPage(PDRectangle.A4)
+ } else {
+ PDPage(PDRectangle(bitmap.width.toFloat(), bitmap.height.toFloat()))
+ }
+ doc.addPage(page)
+
+ PDPageContentStream(doc, page).use { content ->
+ val box = page.mediaBox
+ if (fitToA4) {
+ val scale = minOf(box.width / bitmap.width, box.height / bitmap.height)
+ val w = bitmap.width * scale
+ val h = bitmap.height * scale
+ val x = (box.width - w) / 2f
+ val y = (box.height - h) / 2f
+ content.drawImage(pdImage, x, y, w, h)
+ } else {
+ content.drawImage(pdImage, 0f, 0f, box.width, box.height)
+ }
+ }
+ pages++
+ } finally {
+ if (!bitmap.isRecycled) bitmap.recycle()
+ }
+ }
+ if (pages == 0) throw IllegalStateException("No readable images")
+ val out = context.contentResolver.openOutputStream(outputUri)
+ ?: throw IllegalStateException("Cannot write PDF output")
+ out.use { doc.save(it) }
+ } finally {
+ doc.close()
+ }
+ return PdfDocument(uri = outputUri, name = "Converted.pdf", pageCount = pages)
+ }
+
+ override fun extractText(context: Context, source: PdfDocument): String {
+ PdfBox.ensureInitialized(context)
+ val input = context.contentResolver.openInputStream(source.uri)
+ ?: throw IllegalArgumentException("Cannot open source")
+ return input.use { stream ->
+ PDDocument.load(stream).use { doc ->
+ PDFTextStripper().apply { sortByPosition = true }.getText(doc)
+ }
+ }
+ }
+
+ private fun decodeBitmap(context: Context, uri: Uri): Bitmap? {
+ return try {
+ context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) }
+ } catch (_: Exception) {
+ null
+ }
+ }
+}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/editor/PdfEditor.kt b/pdf-core/src/main/java/com/kyant/pdfcore/editor/PdfEditor.kt
new file mode 100644
index 0000000..cbe9c52
--- /dev/null
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/editor/PdfEditor.kt
@@ -0,0 +1,71 @@
+package com.kyant.pdfcore.editor
+
+import android.content.Context
+import android.net.Uri
+import com.kyant.pdfcore.internal.PdfBox
+import com.kyant.pdfcore.model.PdfDocument
+import com.tom_roush.pdfbox.pdmodel.PDDocument
+
+/**
+ * Lossless page-level editing: reorder, delete, and rotate pages while preserving the
+ * original text & vector content. Powers the in-app page organiser.
+ */
+interface PdfEditor {
+
+ /**
+ * Produce a new document from [source] whose pages are exactly [order] (a list of
+ * original 0-based page indices). Omitting an index deletes that page; repeating it
+ * duplicates it; any other ordering reorders. Each entry may carry an extra clockwise
+ * rotation via [rotationByOriginalIndex] (degrees, added to the page's existing
+ * rotation).
+ */
+ fun applyPageEdits(
+ context: Context,
+ source: PdfDocument,
+ order: List<Int>,
+ rotationByOriginalIndex: Map<Int, Int> = emptyMap(),
+ outputUri: Uri
+ ): PdfDocument
+}
+
+class PdfEditorImpl : PdfEditor {
+
+ override fun applyPageEdits(
+ context: Context,
+ source: PdfDocument,
+ order: List<Int>,
+ rotationByOriginalIndex: Map<Int, Int>,
+ outputUri: Uri
+ ): PdfDocument {
+ PdfBox.ensureInitialized(context)
+ if (order.isEmpty()) throw IllegalArgumentException("Result would have no pages")
+
+ val output = PDDocument()
+ var written = 0
+ try {
+ val input = context.contentResolver.openInputStream(source.uri)
+ ?: throw IllegalArgumentException("Cannot open source")
+ input.use { stream ->
+ PDDocument.load(stream).use { doc ->
+ for (orig in order) {
+ if (orig !in 0 until doc.numberOfPages) continue
+ val srcPage = doc.getPage(orig)
+ val imported = output.importPage(srcPage)
+ val extra = rotationByOriginalIndex[orig] ?: 0
+ if (extra != 0) {
+ imported.rotation = (((srcPage.rotation + extra) % 360) + 360) % 360
+ }
+ written++
+ }
+ }
+ }
+ if (written == 0) throw IllegalArgumentException("Result would have no pages")
+ val out = context.contentResolver.openOutputStream(outputUri)
+ ?: throw IllegalStateException("Cannot write edited PDF output")
+ out.use { output.save(it) }
+ } finally {
+ output.close()
+ }
+ return PdfDocument(uri = outputUri, name = "Edited.pdf", pageCount = written)
+ }
+}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/internal/PdfBox.kt b/pdf-core/src/main/java/com/kyant/pdfcore/internal/PdfBox.kt
new file mode 100644
index 0000000..48a9365
--- /dev/null
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/internal/PdfBox.kt
@@ -0,0 +1,26 @@
+package com.kyant.pdfcore.internal
+
+import android.content.Context
+import com.tom_roush.pdfbox.android.PDFBoxResourceLoader
+
+/**
+ * Centralised, idempotent initialisation for PdfBox-Android.
+ *
+ * PdfBox needs its resource loader primed with an Android [Context] before any document
+ * is loaded (it resolves bundled fonts/CMaps through assets). Call [ensureInitialized]
+ * at the top of every entry point that touches PdfBox.
+ */
+internal object PdfBox {
+
+ @Volatile
+ private var initialized = false
+
+ fun ensureInitialized(context: Context) {
+ if (initialized) return
+ synchronized(this) {
+ if (initialized) return
+ PDFBoxResourceLoader.init(context.applicationContext)
+ initialized = true
+ }
+ }
+}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/merger/PdfMerger.kt b/pdf-core/src/main/java/com/kyant/pdfcore/merger/PdfMerger.kt
index 3416731..763ae2c 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/merger/PdfMerger.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/merger/PdfMerger.kt
@@ -2,102 +2,51 @@ package com.kyant.pdfcore.merger
import android.content.Context
import android.net.Uri
+import com.kyant.pdfcore.internal.PdfBox
import com.kyant.pdfcore.model.PdfDocument
+import com.tom_roush.pdfbox.io.MemoryUsageSetting
+import com.tom_roush.pdfbox.multipdf.PDFMergerUtility
+import com.tom_roush.pdfbox.pdmodel.PDDocument
/**
* Merges two or more PDF files into a single output document.
- *
- * Implementations may use iText, PDFBox-Android, or a native solution.
*/
interface PdfMerger {
- /**
- * Merge a list of PDF [sources] into one document written to [outputUri].
- *
- * @param context Application context for content resolution.
- * @param sources Ordered list of PDFs to merge.
- * @param outputUri Destination URI for the merged file.
- * @return A [PdfDocument] describing the merged output.
- */
- fun merge(
- context: Context,
- sources: List<PdfDocument>,
- outputUri: Uri
- ): PdfDocument
+ /** Merge a list of PDF [sources] (whole documents) into one file at [outputUri]. */
+ fun merge(context: Context, sources: List<PdfDocument>, outputUri: Uri): PdfDocument
- /**
- * Merge only selected pages from each source.
- *
- * @param context Application context.
- * @param sources List of pairs: (document, page-indices to include).
- * @param outputUri Destination URI.
- * @return A [PdfDocument] describing the merged output.
- */
- fun mergePages(
- context: Context,
- sources: List<Pair<PdfDocument, List<Int>>>,
- outputUri: Uri
- ): PdfDocument
+ /** Merge only selected pages from each source. */
+ fun mergePages(context: Context, sources: List<Pair<PdfDocument, List<Int>>>, outputUri: Uri): PdfDocument
}
/**
- * Real implementation using Android's PdfRenderer + PdfDocument APIs.
+ * Lossless implementation using PdfBox — pages are copied with their original text and
+ * vector content intact (no rasterisation, no quality loss, output stays small).
*/
class PdfMergerImpl : PdfMerger {
- override fun merge(
- context: Context,
- sources: List<PdfDocument>,
- outputUri: Uri
- ): PdfDocument {
- val outDoc = android.graphics.pdf.PdfDocument()
- var globalPage = 0
- var reusableBitmap: android.graphics.Bitmap? = null
+ override fun merge(context: Context, sources: List<PdfDocument>, outputUri: Uri): PdfDocument {
+ PdfBox.ensureInitialized(context)
+ if (sources.isEmpty()) throw IllegalArgumentException("No PDFs to merge")
- try {
- for (src in sources) {
- context.contentResolver.openFileDescriptor(src.uri, "r")?.use { fd ->
- val renderer = android.graphics.pdf.PdfRenderer(fd)
- try {
- for (i in 0 until renderer.pageCount) {
- val srcPage = renderer.openPage(i)
- try {
- val w = srcPage.width
- val h = srcPage.height
- val bitmap = obtainReusableBitmap(reusableBitmap, w, h)
- if (bitmap !== reusableBitmap) {
- reusableBitmap?.recycle()
- reusableBitmap = bitmap
- }
- bitmap.eraseColor(android.graphics.Color.WHITE)
- srcPage.render(bitmap, null, null, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_PRINT)
+ val merger = PDFMergerUtility()
+ val outputStream = context.contentResolver.openOutputStream(outputUri)
+ ?: throw IllegalStateException("Cannot write merged PDF output")
- val pageInfo = android.graphics.pdf.PdfDocument.PageInfo.Builder(w, h, globalPage++).create()
- val page = outDoc.startPage(pageInfo)
- page.canvas.drawBitmap(bitmap, 0f, 0f, null)
- outDoc.finishPage(page)
- } finally {
- srcPage.close()
- }
- }
- } finally {
- renderer.close()
- }
- }
- }
-
- val mergeOutput = context.contentResolver.openOutputStream(outputUri)
- ?: throw IllegalStateException("Cannot write merged PDF output")
- mergeOutput.use {
- outDoc.writeTo(it)
- it.flush()
+ var totalPages = 0
+ outputStream.use { out ->
+ merger.destinationStream = out
+ for (src in sources) {
+ val input = context.contentResolver.openInputStream(src.uri)
+ ?: throw IllegalStateException("Cannot read ${src.name}")
+ merger.addSource(input)
+ totalPages += countPages(context, src.uri)
}
- } finally {
- reusableBitmap?.recycle()
- outDoc.close()
+ merger.mergeDocuments(MemoryUsageSetting.setupTempFileOnly())
}
- return PdfDocument(uri = outputUri, name = "Merged.pdf", pageCount = globalPage)
+ return PdfDocument(uri = outputUri, name = "Merged.pdf", pageCount = totalPages)
}
override fun mergePages(
@@ -105,65 +54,41 @@ class PdfMergerImpl : PdfMerger {
sources: List<Pair<PdfDocument, List<Int>>>,
outputUri: Uri
): PdfDocument {
- val outDoc = android.graphics.pdf.PdfDocument()
- var globalPage = 0
- var reusableBitmap: android.graphics.Bitmap? = null
+ PdfBox.ensureInitialized(context)
+ val output = PDDocument()
+ var written = 0
try {
for ((src, pages) in sources) {
- context.contentResolver.openFileDescriptor(src.uri, "r")?.use { fd ->
- val renderer = android.graphics.pdf.PdfRenderer(fd)
- try {
+ val input = context.contentResolver.openInputStream(src.uri)
+ ?: throw IllegalStateException("Cannot read ${src.name}")
+ input.use { stream ->
+ PDDocument.load(stream).use { doc ->
for (i in pages) {
- if (i < 0 || i >= renderer.pageCount) continue
- val srcPage = renderer.openPage(i)
- try {
- val w = srcPage.width
- val h = srcPage.height
- val bitmap = obtainReusableBitmap(reusableBitmap, w, h)
- if (bitmap !== reusableBitmap) {
- reusableBitmap?.recycle()
- reusableBitmap = bitmap
- }
- bitmap.eraseColor(android.graphics.Color.WHITE)
- srcPage.render(bitmap, null, null, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_PRINT)
-
- val pageInfo = android.graphics.pdf.PdfDocument.PageInfo.Builder(w, h, globalPage++).create()
- val page = outDoc.startPage(pageInfo)
- page.canvas.drawBitmap(bitmap, 0f, 0f, null)
- outDoc.finishPage(page)
- } finally {
- srcPage.close()
+ if (i in 0 until doc.numberOfPages) {
+ output.importPage(doc.getPage(i))
+ written++
}
}
- } finally {
- renderer.close()
}
}
}
-
- val mergePagesOutput = context.contentResolver.openOutputStream(outputUri)
+ val out = context.contentResolver.openOutputStream(outputUri)
?: throw IllegalStateException("Cannot write merged PDF output")
- mergePagesOutput.use {
- outDoc.writeTo(it)
- it.flush()
- }
+ out.use { output.save(it) }
} finally {
- reusableBitmap?.recycle()
- outDoc.close()
+ output.close()
}
- return PdfDocument(uri = outputUri, name = "Merged.pdf", pageCount = globalPage)
+ return PdfDocument(uri = outputUri, name = "Merged.pdf", pageCount = written)
}
- private fun obtainReusableBitmap(
- existing: android.graphics.Bitmap?,
- width: Int,
- height: Int
- ): android.graphics.Bitmap {
- if (existing != null && !existing.isRecycled && existing.width == width && existing.height == height) {
- return existing
- }
- return android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888)
+ /** Cheap page count via the native renderer (no full PdfBox parse). */
+ private fun countPages(context: Context, uri: Uri): Int = try {
+ context.contentResolver.openFileDescriptor(uri, "r")?.use { fd ->
+ android.graphics.pdf.PdfRenderer(fd).use { it.pageCount }
+ } ?: 0
+ } catch (_: Exception) {
+ 0
}
}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/splitter/PdfSplitter.kt b/pdf-core/src/main/java/com/kyant/pdfcore/splitter/PdfSplitter.kt
index d59ae8c..dcbaa53 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/splitter/PdfSplitter.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/splitter/PdfSplitter.kt
@@ -2,136 +2,77 @@ package com.kyant.pdfcore.splitter
import android.content.Context
import android.net.Uri
+import com.kyant.pdfcore.internal.PdfBox
import com.kyant.pdfcore.model.PdfDocument
+import com.tom_roush.pdfbox.pdmodel.PDDocument
+import java.io.File
/**
- * Splits a PDF into multiple documents.
+ * Splits a PDF into multiple documents (lossless — original page content is preserved).
*/
interface PdfSplitter {
- /**
- * Split a PDF into individual page PDFs.
- */
+
+ /** Split a PDF into one single-page PDF per page, written into the cache dir. */
fun splitAll(context: Context, source: PdfDocument, outputDir: Uri): List<PdfDocument>
- /**
- * Extract specific pages from a PDF into a new document.
- */
+ /** Extract specific [pages] from a PDF into a new document at [outputUri]. */
fun extractPages(context: Context, source: PdfDocument, pages: List<Int>, outputUri: Uri): PdfDocument
}
class PdfSplitterImpl : PdfSplitter {
override fun splitAll(context: Context, source: PdfDocument, outputDir: Uri): List<PdfDocument> {
- // Split into individual pages - each saved via content resolver
+ PdfBox.ensureInitialized(context)
val results = mutableListOf<PdfDocument>()
- context.contentResolver.openFileDescriptor(source.uri, "r")?.use { fd ->
- val renderer = android.graphics.pdf.PdfRenderer(fd)
- var reusableBitmap: android.graphics.Bitmap? = null
- try {
- for (i in 0 until renderer.pageCount) {
- val srcPage = renderer.openPage(i)
- try {
- val w = srcPage.width
- val h = srcPage.height
- val bitmap = obtainReusableBitmap(reusableBitmap, w, h)
- if (bitmap !== reusableBitmap) {
- reusableBitmap?.recycle()
- reusableBitmap = bitmap
- }
- bitmap.eraseColor(android.graphics.Color.WHITE)
- srcPage.render(bitmap, null, null, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_PRINT)
+ val baseName = source.name.removeSuffix(".pdf").ifBlank { "Document" }
+ val splitDir = File(context.cacheDir, "split").apply { mkdirs() }
- val outDoc = android.graphics.pdf.PdfDocument()
- try {
- val pageInfo = android.graphics.pdf.PdfDocument.PageInfo.Builder(w, h, 0).create()
- val page = outDoc.startPage(pageInfo)
- page.canvas.drawBitmap(bitmap, 0f, 0f, null)
- outDoc.finishPage(page)
-
- // Write to cache and record
- val baseName = source.name.removeSuffix(".pdf")
- val fileName = "${baseName}_page${i + 1}.pdf"
- val outFile = java.io.File(context.cacheDir, fileName)
- outFile.outputStream().use {
- outDoc.writeTo(it)
- it.flush()
- }
- results.add(PdfDocument(uri = Uri.fromFile(outFile), name = fileName, pageCount = 1))
- } finally {
- outDoc.close()
- }
- } finally {
- srcPage.close()
+ val input = context.contentResolver.openInputStream(source.uri)
+ ?: throw IllegalArgumentException("Cannot open source")
+ input.use { stream ->
+ PDDocument.load(stream).use { doc ->
+ for (i in 0 until doc.numberOfPages) {
+ PDDocument().use { single ->
+ single.importPage(doc.getPage(i))
+ val fileName = "${baseName}_page${i + 1}.pdf"
+ val outFile = File(splitDir, fileName)
+ outFile.outputStream().use { single.save(it) }
+ results.add(PdfDocument(uri = Uri.fromFile(outFile), name = fileName, pageCount = 1))
}
}
- } finally {
- reusableBitmap?.recycle()
- renderer.close()
}
- } ?: return results
-
+ }
return results
}
- override fun extractPages(context: Context, source: PdfDocument, pages: List<Int>, outputUri: Uri): PdfDocument {
- val outDoc = android.graphics.pdf.PdfDocument()
- var writtenPages = 0
-
+ override fun extractPages(
+ context: Context,
+ source: PdfDocument,
+ pages: List<Int>,
+ outputUri: Uri
+ ): PdfDocument {
+ PdfBox.ensureInitialized(context)
+ var written = 0
+ val output = PDDocument()
try {
- context.contentResolver.openFileDescriptor(source.uri, "r")?.use { fd ->
- val renderer = android.graphics.pdf.PdfRenderer(fd)
- var reusableBitmap: android.graphics.Bitmap? = null
- try {
- for (pageIdx in pages) {
- if (pageIdx < 0 || pageIdx >= renderer.pageCount) continue
- val srcPage = renderer.openPage(pageIdx)
- try {
- val w = srcPage.width
- val h = srcPage.height
- val bitmap = obtainReusableBitmap(reusableBitmap, w, h)
- if (bitmap !== reusableBitmap) {
- reusableBitmap?.recycle()
- reusableBitmap = bitmap
- }
- bitmap.eraseColor(android.graphics.Color.WHITE)
- srcPage.render(bitmap, null, null, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_PRINT)
-
- val pageInfo = android.graphics.pdf.PdfDocument.PageInfo.Builder(w, h, writtenPages).create()
- val page = outDoc.startPage(pageInfo)
- page.canvas.drawBitmap(bitmap, 0f, 0f, null)
- outDoc.finishPage(page)
- writtenPages += 1
- } finally {
- srcPage.close()
+ val input = context.contentResolver.openInputStream(source.uri)
+ ?: throw IllegalArgumentException("Cannot open source")
+ input.use { stream ->
+ PDDocument.load(stream).use { doc ->
+ for (i in pages) {
+ if (i in 0 until doc.numberOfPages) {
+ output.importPage(doc.getPage(i))
+ written++
}
}
- } finally {
- reusableBitmap?.recycle()
- renderer.close()
}
- } ?: throw IllegalArgumentException("Cannot open source")
-
- val splitOutput = context.contentResolver.openOutputStream(outputUri)
- ?: throw IllegalStateException("Cannot write split PDF output")
- splitOutput.use {
- outDoc.writeTo(it)
- it.flush()
}
+ val out = context.contentResolver.openOutputStream(outputUri)
+ ?: throw IllegalStateException("Cannot write split PDF output")
+ out.use { output.save(it) }
} finally {
- outDoc.close()
- }
-
- return PdfDocument(uri = outputUri, name = "Split.pdf", pageCount = writtenPages)
- }
-
- private fun obtainReusableBitmap(
- existing: android.graphics.Bitmap?,
- width: Int,
- height: Int
- ): android.graphics.Bitmap {
- if (existing != null && !existing.isRecycled && existing.width == width && existing.height == height) {
- return existing
+ output.close()
}
- return android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888)
+ return PdfDocument(uri = outputUri, name = "Split.pdf", pageCount = written)
}
}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt b/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt
index f6a513b..bc78b62 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/viewer/PdfViewer.kt
@@ -2,22 +2,22 @@ package com.kyant.pdfcore.viewer
import android.content.Context
import android.graphics.Bitmap
+import android.graphics.Matrix
import android.net.Uri
+import android.util.Size
import com.kyant.pdfcore.model.PdfDocument
+import java.util.concurrent.locks.ReentrantLock
+import kotlin.concurrent.withLock
/**
* Provides read-only access to a PDF file — opening, page rendering, and metadata.
*
- * Implementations will use Android's PdfRenderer or a third-party library.
+ * Implementations use Android's [android.graphics.pdf.PdfRenderer].
*/
interface PdfViewer {
/**
* Open a PDF from the given [uri] and return its metadata.
- *
- * @param context Application or activity context for content resolution.
- * @param uri Content URI pointing to the PDF file.
- * @return A [PdfDocument] describing the opened file.
*/
fun open(context: Context, uri: Uri): PdfDocument
@@ -26,10 +26,17 @@ interface PdfViewer {
*
* @param document The document previously returned by [open].
* @param pageIndex Zero-based page index.
- * @param width Desired bitmap width in pixels.
+ * @param width Desired bitmap width in pixels (the rendered output respects
+ * the page aspect ratio; [rotationDegrees] is applied first).
+ * @param rotationDegrees Clockwise rotation to bake into the bitmap (0/90/180/270).
* @return A [Bitmap] of the rendered page, or `null` on failure.
*/
- fun renderPage(document: PdfDocument, pageIndex: Int, width: Int): Bitmap?
+ fun renderPage(document: PdfDocument, pageIndex: Int, width: Int, rotationDegrees: Int = 0): Bitmap?
+
+ /**
+ * Return the natural size (in PDF points) of [pageIndex], or `null` on failure.
+ */
+ fun pageSize(document: PdfDocument, pageIndex: Int): Size?
/**
* Release all resources held for [document].
@@ -38,48 +45,98 @@ interface PdfViewer {
}
/**
- * Default stub implementation. Every method throws [NotImplementedError].
+ * Default implementation backed by [android.graphics.pdf.PdfRenderer].
+ *
+ * `PdfRenderer` allows only a **single open page per renderer at a time** and is not
+ * thread-safe, so every renderer interaction is funnelled through [lock]. This is what
+ * makes it safe for the viewer to pre-render neighbouring pages from parallel coroutines.
*/
class PdfViewerImpl : PdfViewer {
- private val renderers = mutableMapOf<Uri, android.graphics.pdf.PdfRenderer>()
- private val fds = mutableMapOf<Uri, android.os.ParcelFileDescriptor>()
+ private val lock = ReentrantLock()
+ private val renderers = HashMap<Uri, android.graphics.pdf.PdfRenderer>()
+ private val fds = HashMap<Uri, android.os.ParcelFileDescriptor>()
+
+ override fun open(context: Context, uri: Uri): PdfDocument = lock.withLock {
+ // Re-opening the same uri reuses nothing stale.
+ renderers.remove(uri)?.runCatching { close() }
+ fds.remove(uri)?.runCatching { close() }
- override fun open(context: Context, uri: Uri): PdfDocument {
val fd = context.contentResolver.openFileDescriptor(uri, "r")
?: throw IllegalArgumentException("Cannot open file: $uri")
val renderer = android.graphics.pdf.PdfRenderer(fd)
fds[uri] = fd
renderers[uri] = renderer
- val name = queryFileName(context, uri) ?: "Unknown.pdf"
- val size = fd.statSize
-
- return PdfDocument(
+ PdfDocument(
uri = uri,
- name = name,
+ name = queryFileName(context, uri) ?: "Unknown.pdf",
pageCount = renderer.pageCount,
- sizeBytes = size
+ sizeBytes = fd.statSize
)
}
- override fun renderPage(document: PdfDocument, pageIndex: Int, width: Int): Bitmap? {
+ override fun renderPage(document: PdfDocument, pageIndex: Int, width: Int, rotationDegrees: Int): Bitmap? =
+ lock.withLock {
+ val renderer = renderers[document.uri] ?: return null
+ if (pageIndex < 0 || pageIndex >= renderer.pageCount) return null
+
+ val page = renderer.openPage(pageIndex)
+ try {
+ val rotation = ((rotationDegrees % 360) + 360) % 360
+ val swap = rotation == 90 || rotation == 270
+ val srcW = page.width.toFloat().coerceAtLeast(1f)
+ val srcH = page.height.toFloat().coerceAtLeast(1f)
+
+ // Width/height of the *displayed* (post-rotation) page.
+ val dispW = if (swap) srcH else srcW
+ val dispH = if (swap) srcW else srcH
+
+ val targetW = width.coerceAtLeast(1)
+ val targetH = (targetW * (dispH / dispW)).toInt().coerceAtLeast(1)
+
+ val bitmap = Bitmap.createBitmap(targetW, targetH, Bitmap.Config.ARGB_8888)
+ bitmap.eraseColor(android.graphics.Color.WHITE)
+
+ // Map the source page into the (possibly rotated) target bitmap.
+ val matrix = Matrix().apply {
+ if (rotation != 0) {
+ postRotate(rotation.toFloat())
+ // After rotation the content may be in negative space; translate back.
+ when (rotation) {
+ 90 -> postTranslate(srcH, 0f)
+ 180 -> postTranslate(srcW, srcH)
+ 270 -> postTranslate(0f, srcW)
+ }
+ }
+ // Scale rotated content (dispW x dispH) to the target bitmap.
+ postScale(targetW / dispW, targetH / dispH)
+ }
+
+ page.render(bitmap, null, matrix, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
+ bitmap
+ } catch (e: Exception) {
+ null
+ } finally {
+ runCatching { page.close() }
+ }
+ }
+
+ override fun pageSize(document: PdfDocument, pageIndex: Int): Size? = lock.withLock {
val renderer = renderers[document.uri] ?: return null
if (pageIndex < 0 || pageIndex >= renderer.pageCount) return null
-
val page = renderer.openPage(pageIndex)
- val ratio = page.height.toFloat() / page.width.toFloat()
- val height = (width * ratio).toInt()
- val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
- bitmap.eraseColor(android.graphics.Color.WHITE)
- page.render(bitmap, null, null, android.graphics.pdf.PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
- page.close()
- return bitmap
+ try {
+ Size(page.width, page.height)
+ } finally {
+ runCatching { page.close() }
+ }
}
- override fun close(document: PdfDocument) {
- renderers.remove(document.uri)?.close()
- fds.remove(document.uri)?.close()
+ override fun close(document: PdfDocument) = lock.withLock {
+ renderers.remove(document.uri)?.runCatching { close() }
+ fds.remove(document.uri)?.runCatching { close() }
+ Unit
}
private fun queryFileName(context: Context, uri: Uri): String? {
@@ -90,6 +147,8 @@ class PdfViewerImpl : PdfViewer {
if (idx >= 0) cursor.getString(idx) else null
} else null
}
- } catch (_: Exception) { null }
+ } catch (_: Exception) {
+ null
+ }
}
}
diff --git a/readme.md b/readme.md
index ee6b2ab..a97e5a0 100644
--- a/readme.md
+++ b/readme.md
@@ -19,16 +19,18 @@
# ✨ Features
-- 📖 Fast and lightweight PDF reader
-- 🔀 Merge multiple PDFs
-- ✂️ Split and extract PDF pages
+- 📖 Fast PDF reader with smooth, Adobe-style pinch-zoom & pan
+- ✍️ Annotate: pen, highlighter, shapes, arrows + on-device text selection (OCR)
+- 🗂️ Organize pages: reorder, rotate & delete — losslessly
+- 🔀 Merge multiple PDFs (lossless — text & vectors preserved)
+- ✂️ Split and extract PDF pages (lossless)
- 🗜️ Compress PDFs with quality controls
-- 📄 Create PDFs from images, scans, or blank pages
-- 📷 Document scanner with edge detection
+- 🖼️ Images → PDF and 📄 Create PDFs from scans or blank pages
+- 🔎 Extract text from PDFs (copy / share)
+- 📷 Document scanner with edge detection (Google ML Kit)
- 🌗 Beautiful liquid glass UI for light & dark mode
- ⚡ Smooth performance built with Jetpack Compose
-- 🔒 Offline-first and privacy friendly
-- 🎨 Modern Android experience
+- 🔒 Fully offline & privacy friendly — no cloud, no accounts
---
@@ -108,7 +110,12 @@ Liquid glass and backdrop effects are inspired by and partially adapted from:
AndroidLiquidGlass by kyant0
https://github.com/Kyant0/AndroidLiquidGlass
-Licensed under Apache License 2.0.
+Lossless PDF page operations and text extraction are powered by:
+
+PdfBox-Android by Tom Roush (a port of Apache PDFBox)
+https://github.com/TomRoush/PdfBox-Android
+
+Both are licensed under the Apache License 2.0.
---