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.

Dark reading keeps photos; viewers follow the reader mode, not the theme

chethan616ff5909cb8151
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/NightPaper.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/NightPaper.kt
new file mode 100644
index 0000000..b63bbf9
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/NightPaper.kt
@@ -0,0 +1,84 @@
+package com.chethan616.clearpdf.ui.components
+
+import android.graphics.Bitmap
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.ColorFilter
+import androidx.compose.ui.graphics.ColorMatrix
+
+/**
+ * Dark reader mode for documents ("night"), after Gander (MIT): the page's colours are turned over
+ * with invert + a 180° hue turn, so white paper goes black and black ink white while a blue heading
+ * stays blue (a plain RGB invert made it orange). Pictures are judged one by one: a scan or a
+ * figure on white "looks like paper" and turns over with the page; a photograph is left exactly as
+ * it was printed.
+ */
+object NightPaper {
+
+ /** invert(1) hue-rotate(180deg) — Gander's VW_NIGHT_MATRIX, offsets in 0..255. */
+ private val matrix = floatArrayOf(
+ 0.574f, -1.430f, -0.144f, 0f, 255f,
+ -0.426f, -0.430f, -0.144f, 0f, 255f,
+ -0.426f, -1.430f, 0.856f, 0f, 255f,
+ 0f, 0f, 0f, 1f, 0f
+ )
+
+ val filter: ColorFilter = ColorFilter.colorMatrix(ColorMatrix(matrix))
+
+ /** One colour as night shows it. */
+ fun color(c: Color): Color {
+ val r = c.red; val g = c.green; val b = c.blue
+ fun ch(i: Int) = (matrix[i] * r + matrix[i + 1] * g + matrix[i + 2] * b + matrix[i + 4] / 255f).coerceIn(0f, 1f)
+ return Color(ch(0), ch(5), ch(10), c.alpha)
+ }
+
+ fun argb(argb: Int): Int {
+ val c = color(Color(argb))
+ return android.graphics.Color.argb(
+ (c.alpha * 255).toInt(), (c.red * 255).toInt(), (c.green * 255).toInt(), (c.blue * 255).toInt()
+ )
+ }
+
+ private const val ProbeWidth = 64
+ private const val ProbeSaturation = 0.15f
+ private const val ProbePaper = 0.25f
+
+ /**
+ * Whether [region] (normalised 0..1, null for the whole bitmap) of [bitmap] is paper — mostly
+ * pale and nearly colourless, like a scan, a chart or a diagram — rather than a photograph.
+ * pdf.js's looksLikePaper thresholds, measured over white (what shows through transparency).
+ */
+ fun looksLikePaper(bitmap: Bitmap, region: Rect? = null): Boolean {
+ if (bitmap.isRecycled || bitmap.width <= 0 || bitmap.height <= 0) return true
+ val l = ((region?.left ?: 0f) * bitmap.width).toInt().coerceIn(0, bitmap.width - 1)
+ val t = ((region?.top ?: 0f) * bitmap.height).toInt().coerceIn(0, bitmap.height - 1)
+ val r = ((region?.right ?: 1f) * bitmap.width).toInt().coerceIn(l + 1, bitmap.width)
+ val b = ((region?.bottom ?: 1f) * bitmap.height).toInt().coerceIn(t + 1, bitmap.height)
+ val w = r - l
+ val h = b - t
+ val cols = minOf(ProbeWidth, w).coerceAtLeast(1)
+ val rows = (cols * h / w).coerceIn(1, ProbeWidth * 4)
+ var pale = 0
+ var sat = 0f
+ var n = 0
+ for (yi in 0 until rows) {
+ val y = t + ((yi + 0.5f) * h / rows).toInt().coerceIn(0, h - 1)
+ for (xi in 0 until cols) {
+ val x = l + ((xi + 0.5f) * w / cols).toInt().coerceIn(0, w - 1)
+ val p = bitmap.getPixel(x, y)
+ val a = (p ushr 24) / 255f
+ // Over white.
+ val pr = ((p shr 16 and 0xFF) * a + 255 * (1 - a))
+ val pg = ((p shr 8 and 0xFF) * a + 255 * (1 - a))
+ val pb = ((p and 0xFF) * a + 255 * (1 - a))
+ val mx = maxOf(pr, pg, pb)
+ val mn = minOf(pr, pg, pb)
+ if (mn > 204f) pale++
+ if (mx > 0f) sat += (mx - mn) / mx
+ n++
+ }
+ }
+ if (n == 0) return true
+ return sat / n < ProbeSaturation && pale.toFloat() / n > ProbePaper
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt
index 6c12085..8ed9fc4 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfContinuousPage.kt
@@ -62,6 +62,7 @@ import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
+import com.chethan616.clearpdf.ui.components.NightPaper
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
@@ -125,6 +126,8 @@ internal fun PdfContinuousPage(
backdrop: LayerBackdrop,
bitmap: Bitmap?,
darkPageAppearance: Boolean = false,
+ /** Dark reader: photographs on this page (normalised rects), drawn as printed over the night page. */
+ nightPhotos: List<Rect> = emptyList(),
marks: MutableList<PdfMarkup>,
/** Exact renders of this page's in-place text edits, by markup id (see PdfTextEditPreview). */
textEditPatches: Map<Long, TextEditPatch> = emptyMap(),
@@ -258,20 +261,7 @@ internal fun PdfContinuousPage(
contentDescription = null,
contentScale = ContentScale.FillWidth,
modifier = Modifier.fillMaxWidth(),
- colorFilter = if (darkPageAppearance) {
- remember {
- ColorFilter.colorMatrix(
- ColorMatrix(
- floatArrayOf(
- -1f, 0f, 0f, 0f, 255f,
- 0f, -1f, 0f, 0f, 255f,
- 0f, 0f, -1f, 0f, 255f,
- 0f, 0f, 0f, 1f, 0f
- )
- )
- )
- }
- } else null
+ colorFilter = if (darkPageAppearance) NightPaper.filter else null
)
// The image fills the box width and the box height follows it, so the content
@@ -279,6 +269,11 @@ internal fun PdfContinuousPage(
Canvas(Modifier.matchParentSize()) {
val frame = Rect(0f, 0f, size.width, size.height)
+ // Night: photographs go back to how they were printed (the page around them stays turned).
+ if (darkPageAppearance && !bitmap.isRecycled) {
+ nightPhotos.forEach { r -> drawRegion(bitmap, Rect(0f, 0f, 1f, 1f), r) }
+ }
+
// Sharp zoom: the visible part of the page at screen resolution, over the page bitmap.
detailTile?.takeIf { !it.bitmap.isRecycled }?.let { tile ->
val g = tile.region
@@ -296,6 +291,13 @@ internal fun PdfContinuousPage(
filterQuality = androidx.compose.ui.graphics.FilterQuality.High,
colorFilter = if (darkPageAppearance) InvertColorFilter else null
)
+ if (darkPageAppearance) {
+ val tileRect = Rect(g.left, g.top, g.right, g.bottom)
+ nightPhotos.forEach { r ->
+ val cut = r.intersect(tileRect)
+ if (cut.width > 0f && cut.height > 0f) drawRegion(tile.bitmap, tileRect, cut)
+ }
+ }
}
// Edited lines first, so highlights and other markups still draw on top: the band of
@@ -372,7 +374,7 @@ internal fun PdfContinuousPage(
// Quick preview until the exact render lands: the old line hidden under the page's own
// paper colour, the new text in the line's size, baseline and closest face.
// Dark reader inverts the page, so the preview inverts with it.
- fun c(x: Color) = if (darkPageAppearance) Color(1f - x.red, 1f - x.green, 1f - x.blue, x.alpha) else x
+ fun c(x: Color) = if (darkPageAppearance) NightPaper.color(x) else x
val pad = markup.fontSize * 0.08f
drawRect(
c(markup.background),
@@ -964,16 +966,34 @@ internal fun PdfContinuousPage(
}
}
-private val InvertColorFilter = ColorFilter.colorMatrix(
- ColorMatrix(
- floatArrayOf(
- -1f, 0f, 0f, 0f, 255f,
- 0f, -1f, 0f, 0f, 255f,
- 0f, 0f, -1f, 0f, 255f,
- 0f, 0f, 0f, 1f, 0f
- )
+/** Dark reader's page colours: Gander's hue-keeping turn, not a plain invert (blue stays blue). */
+private val InvertColorFilter = NightPaper.filter
+
+/**
+ * Draws the part [part] (normalised to the page) of [source], which itself covers [sourceRegion]
+ * of the page, unfiltered at its place on this page.
+ */
+private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawRegion(source: Bitmap, sourceRegion: Rect, part: Rect) {
+ val sw = sourceRegion.width.takeIf { it > 0f } ?: return
+ val sh = sourceRegion.height.takeIf { it > 0f } ?: return
+ val sx = ((part.left - sourceRegion.left) / sw * source.width).roundToInt().coerceIn(0, source.width - 1)
+ val sy = ((part.top - sourceRegion.top) / sh * source.height).roundToInt().coerceIn(0, source.height - 1)
+ val sx2 = ((part.right - sourceRegion.left) / sw * source.width).roundToInt().coerceIn(sx + 1, source.width)
+ val sy2 = ((part.bottom - sourceRegion.top) / sh * source.height).roundToInt().coerceIn(sy + 1, source.height)
+ val dx = (part.left * size.width).roundToInt()
+ val dy = (part.top * size.height).roundToInt()
+ drawImage(
+ image = source.asImageBitmap(),
+ srcOffset = IntOffset(sx, sy),
+ srcSize = androidx.compose.ui.unit.IntSize(sx2 - sx, sy2 - sy),
+ dstOffset = IntOffset(dx, dy),
+ dstSize = androidx.compose.ui.unit.IntSize(
+ ((part.right * size.width).roundToInt() - dx).coerceAtLeast(1),
+ ((part.bottom * size.height).roundToInt() - dy).coerceAtLeast(1)
+ ),
+ filterQuality = androidx.compose.ui.graphics.FilterQuality.High
)
-)
+}
private val MarkupBarWidth = 236.dp
private val MarkupBarHeight = 48.dp
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 6de099f..f3fe074 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
@@ -244,7 +244,10 @@ fun PdfViewerScreen(
// dark; the moon button still switches it per document.
val autoDarkPages = com.chethan616.clearpdf.ui.theme.LocalIsDarkMode.current &&
remember { com.chethan616.clearpdf.data.repository.AppSettingsManager.getAutoDarkPages(context) }
- var darkPageAppearance by rememberSaveable { mutableStateOf(autoDarkPages) }
+ // Only the moon button's choice is saved; until it is used the pages follow the theme, so a
+ // first frame drawn before the theme setting applies can't freeze the wrong colours.
+ var darkPageOverride by rememberSaveable { mutableStateOf<Boolean?>(null) }
+ val darkPageAppearance = darkPageOverride ?: autoDarkPages
var bookmarkedPages by remember { mutableStateOf<List<Int>>(emptyList()) }
// Annotation (text box / sticky note) editing
var editingAnnoId by remember { mutableStateOf<Long?>(null) }
@@ -1287,11 +1290,16 @@ fun PdfViewerScreen(
LaunchedEffect(page, renderWidthPx, needsRender) {
if (needsRender) viewModel.renderPage(context, page, renderWidthPx)
}
+ // Dark reader keeps photographs as printed (Gander's night mode).
+ LaunchedEffect(page, darkPageAppearance, needsRender) {
+ if (darkPageAppearance && !needsRender) viewModel.ensureNightPhotos(context, page)
+ }
PdfContinuousPage(
page = page,
backdrop = backdrop,
bitmap = state.pageBitmaps.getOrNull(page),
darkPageAppearance = darkPageAppearance,
+ nightPhotos = if (darkPageAppearance) viewModel.nightPhotos[page].orEmpty() else emptyList(),
marks = getPageMarks(page),
textEditPatches = textEditPatches,
detailTile = detailTiles[page],
@@ -1574,7 +1582,7 @@ fun PdfViewerScreen(
Icon(Icons.Rounded.Search, stringResource(R.string.viewer_find), Modifier.size(20.dp), topFg)
}
LiquidIconButton(
- onClick = { darkPageAppearance = !darkPageAppearance },
+ onClick = { darkPageOverride = !darkPageAppearance },
backdrop = contentBackdrop
) {
Icon(
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetViewerScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetViewerScreen.kt
index 0624bac..c79a6fe 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetViewerScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/SpreadsheetViewerScreen.kt
@@ -218,6 +218,36 @@ fun SpreadsheetViewerScreen(
viewModel: SpreadsheetViewModel,
onBack: () -> Unit,
onOpenPdf: (android.net.Uri) -> Unit = {}
+) {
+ // The sheet is white paper like Excel's (#71), whatever the app theme; the moon button (or
+ // Settings > Dark pages in dark mode) turns it dark, like a PDF's pages. The whole screen then
+ // follows the sheet, not the app theme: desk, glass chrome, menus and dialogs take their ink
+ // from what they sit on (DESIGN.md).
+ val appDark = LocalIsDarkMode.current
+ val context = LocalContext.current
+ val autoDarkSheet = appDark && remember { com.chethan616.clearpdf.data.repository.AppSettingsManager.getAutoDarkPages(context) }
+ var sheetDarkOverride by androidx.compose.runtime.saveable.rememberSaveable { mutableStateOf<Boolean?>(null) }
+ val sheetDark = sheetDarkOverride ?: autoDarkSheet
+ val view = androidx.compose.ui.platform.LocalView.current
+ androidx.compose.runtime.DisposableEffect(view, sheetDark) {
+ val window = (view.context as? android.app.Activity ?: (view.context as? android.content.ContextWrapper)?.baseContext as? android.app.Activity)?.window
+ val ctrl = window?.let { androidx.core.view.WindowCompat.getInsetsController(it, view) }
+ ctrl?.isAppearanceLightStatusBars = !sheetDark
+ onDispose { ctrl?.isAppearanceLightStatusBars = !appDark }
+ }
+ androidx.compose.runtime.CompositionLocalProvider(LocalIsDarkMode provides sheetDark) {
+ SpreadsheetViewerContent(backdrop, viewModel, onBack, onOpenPdf, sheetDark) { sheetDarkOverride = !sheetDark }
+ }
+}
+
+@Composable
+private fun SpreadsheetViewerContent(
+ backdrop: LayerBackdrop,
+ viewModel: SpreadsheetViewModel,
+ onBack: () -> Unit,
+ onOpenPdf: (android.net.Uri) -> Unit,
+ sheetDark: Boolean,
+ onToggleSheet: () -> Unit
) {
val state by viewModel.state.collectAsState()
val isDark = LocalIsDarkMode.current
@@ -276,12 +306,8 @@ fun SpreadsheetViewerScreen(
runCatching { listState.scrollToItem(0) }
}
- // The sheet is white paper like Excel's (#71), whatever the app theme; the moon button (or
- // Settings > Dark pages in dark mode) turns it dark, like a PDF's pages.
val sheetContext = androidx.compose.ui.platform.LocalContext.current
- var sheetDark by androidx.compose.runtime.saveable.rememberSaveable {
- mutableStateOf(isDark && com.chethan616.clearpdf.data.repository.AppSettingsManager.getAutoDarkPages(sheetContext))
- }
+ val desk = if (sheetDark) Color(0xFF0D0D0F) else Color(0xFFE3E4E9)
val surface = if (sheetDark) Color(0xFF1C1C1E) else Color.White
val gridColors = remember(sheetDark) {
GridColors(
@@ -499,7 +525,7 @@ fun SpreadsheetViewerScreen(
LiquidIconButton(onClick = { showSearch = true }, backdrop = headerBackdrop) {
Icon(Icons.Rounded.Search, stringResource(R.string.viewer_find), Modifier.size(20.dp), text)
}
- LiquidIconButton(onClick = { sheetDark = !sheetDark }, backdrop = headerBackdrop) {
+ LiquidIconButton(onClick = onToggleSheet, backdrop = headerBackdrop) {
Icon(
if (sheetDark) Icons.Rounded.LightMode else Icons.Rounded.DarkMode,
stringResource(if (sheetDark) R.string.viewer_page_colors_original else R.string.viewer_page_dark_mode),
@@ -523,6 +549,8 @@ fun SpreadsheetViewerScreen(
}
}
) { contentPadding ->
+ // A desk in the sheet's own light or dark, behind the grid, header and dock alike.
+ Box(Modifier.fillMaxSize().background(desk))
when {
state.isLoading -> Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator(color = accent, strokeWidth = 2.5.dp)
@@ -721,11 +749,12 @@ fun SpreadsheetViewerScreen(
matchCount = matches.size,
currentMatchIndex = currentMatch,
focusRequester = searchFocus,
- backdrop = backdrop,
+ // The live sheet behind it, like the PDF viewer's find bar (not just the wallpaper).
+ backdrop = screenBackdrop.content,
uiSensor = uiSensor,
fg = text,
fgSoft = sub,
- surface = chromeGlass,
+ surface = Color.Transparent,
onQueryChange = { searchQuery = it },
onPrevMatch = { goToMatch(-1) },
onNextMatch = { goToMatch(1) },
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 f8c1eb3..433be64 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
@@ -221,6 +221,52 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
// time, capping the peak to a single in-flight copy. Pages still extract lazily; they just queue.
private val textExtractionMutex = Mutex()
+ /**
+ * Dark reader: per page, the photographs to draw as printed over the turned-over page, as
+ * rectangles normalised to the page (see [com.kyant.pdfcore.image.PdfImageRegions]). Filled
+ * only while dark pages are on, a few pages around the one asked for at a time.
+ */
+ val nightPhotos = androidx.compose.runtime.mutableStateMapOf<Int, List<androidx.compose.ui.geometry.Rect>>()
+ private val pictureRects = HashMap<Int, List<android.graphics.RectF>>()
+ private val pictureScanning = HashSet<Int>()
+
+ fun ensureNightPhotos(context: Context, pageIndex: Int) {
+ val doc = _uiState.value.document ?: return
+ if (nightPhotos.containsKey(pageIndex)) return
+ val uri = doc.uri
+ val raw = pictureRects[pageIndex]
+ if (raw != null) { classifyNightPhotos(pageIndex, raw); return }
+ val batch = ((pageIndex - 2)..(pageIndex + 5)).filter { it in 0 until doc.pageCount && it !in pictureRects && it !in pictureScanning }
+ if (pageIndex !in batch) return
+ pictureScanning.addAll(batch)
+ viewModelScope.launch {
+ val found = withContext(AppDispatchers.pdf) {
+ textExtractionMutex.withLock {
+ runCatching { com.kyant.pdfcore.image.PdfImageRegions.pages(context, uri, batch) }.getOrDefault(emptyMap())
+ }
+ }
+ pictureScanning.removeAll(batch.toSet())
+ if (_uiState.value.document?.uri != uri) return@launch
+ for (p in batch) pictureRects[p] = found[p] ?: emptyList()
+ classifyNightPhotos(pageIndex, pictureRects[pageIndex].orEmpty())
+ }
+ }
+
+ /** Keeps the pictures that are photographs; scans and figures on white turn over with the page. */
+ private fun classifyNightPhotos(pageIndex: Int, rects: List<android.graphics.RectF>) {
+ if (rects.isEmpty()) { nightPhotos[pageIndex] = emptyList(); return }
+ val uri = _uiState.value.document?.uri ?: return
+ val bitmap = _uiState.value.pageBitmaps.getOrNull(pageIndex)?.takeIf { !it.isRecycled } ?: return
+ viewModelScope.launch {
+ val photos = withContext(kotlinx.coroutines.Dispatchers.Default) {
+ rects.map { androidx.compose.ui.geometry.Rect(it.left, it.top, it.right, it.bottom) }.filter { r ->
+ runCatching { !com.chethan616.clearpdf.ui.components.NightPaper.looksLikePaper(bitmap, r) }.getOrDefault(false)
+ }
+ }
+ if (_uiState.value.document?.uri == uri) nightPhotos[pageIndex] = photos
+ }
+ }
+
private val textService = PdfServiceLocator.pdfTextService
companion object {
@@ -248,6 +294,9 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
pendingRenderWidths.clear()
renderedPageWidths.clear()
textLoadingPages.clear()
+ nightPhotos.clear()
+ pictureRects.clear()
+ pictureScanning.clear()
_uiState.value = _uiState.value.copy(
isLoading = true,
// A supplied password means this call is the actual unlock → drive the decrypt animation.
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/image/PdfImageRegions.kt b/pdf-core/src/main/java/com/kyant/pdfcore/image/PdfImageRegions.kt
new file mode 100644
index 0000000..a8fa585
--- /dev/null
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/image/PdfImageRegions.kt
@@ -0,0 +1,89 @@
+package com.kyant.pdfcore.image
+
+import android.content.Context
+import android.graphics.Path
+import android.graphics.PointF
+import android.graphics.RectF
+import android.net.Uri
+import com.kyant.pdfcore.internal.PdfBox
+import com.tom_roush.pdfbox.contentstream.PDFGraphicsStreamEngine
+import com.tom_roush.pdfbox.cos.COSName
+import com.tom_roush.pdfbox.pdmodel.PDDocument
+import com.tom_roush.pdfbox.pdmodel.PDPage
+import com.tom_roush.pdfbox.pdmodel.graphics.image.PDImage
+
+/**
+ * Where a page draws its pictures, as rectangles in the page's displayed space (rotation and crop
+ * box applied) normalised to 0..1, so they line up with a rendered page bitmap of any size.
+ *
+ * Night mode turns a page's colours over; the viewer uses these to put photographs back the way
+ * they were printed, the way Gander (MIT) does it for pdf.js.
+ */
+object PdfImageRegions {
+
+ fun pages(context: Context, uri: Uri, pages: Collection<Int>): Map<Int, List<RectF>> {
+ PdfBox.ensureInitialized(context)
+ val out = HashMap<Int, List<RectF>>()
+ context.contentResolver.openInputStream(uri)?.use { stream ->
+ PDDocument.load(stream).use { doc ->
+ for (i in pages) {
+ if (i !in 0 until doc.numberOfPages) continue
+ out[i] = runCatching { page(doc.getPage(i)) }.getOrDefault(emptyList())
+ }
+ }
+ }
+ return out
+ }
+
+ fun page(page: PDPage): List<RectF> {
+ val box = page.cropBox
+ val x0 = box.lowerLeftX
+ val y0 = box.lowerLeftY
+ val w = box.width.takeIf { it > 0f } ?: return emptyList()
+ val h = box.height.takeIf { it > 0f } ?: return emptyList()
+ val rotation = ((page.rotation % 360) + 360) % 360
+ val found = ArrayList<RectF>()
+
+ val engine = object : PDFGraphicsStreamEngine(page) {
+ override fun drawImage(pdImage: PDImage) {
+ val m = graphicsState.currentTransformationMatrix
+ var minX = Float.MAX_VALUE; var minY = Float.MAX_VALUE
+ var maxX = -Float.MAX_VALUE; var maxY = -Float.MAX_VALUE
+ // The image fills the unit square of its transformation matrix.
+ for ((ux, uy) in arrayOf(0f to 0f, 1f to 0f, 0f to 1f, 1f to 1f)) {
+ val px = m.scaleX * ux + m.shearX * uy + m.translateX
+ val py = m.shearY * ux + m.scaleY * uy + m.translateY
+ // Normalised display coordinates, top-left origin.
+ val nx = (px - x0) / w
+ val ny = (py - y0) / h
+ val (dx, dy) = when (rotation) {
+ 90 -> ny to nx
+ 180 -> (1f - nx) to ny
+ 270 -> (1f - ny) to (1f - nx)
+ else -> nx to (1f - ny)
+ }
+ minX = minOf(minX, dx); maxX = maxOf(maxX, dx)
+ minY = minOf(minY, dy); maxY = maxOf(maxY, dy)
+ }
+ val r = RectF(minX.coerceIn(0f, 1f), minY.coerceIn(0f, 1f), maxX.coerceIn(0f, 1f), maxY.coerceIn(0f, 1f))
+ // Tiny pictures (bullets, rules) and slivers aren't worth a pass of their own.
+ if (r.width() * r.height() > 0.0004f && r.width() > 0.01f && r.height() > 0.01f) found.add(r)
+ }
+
+ override fun appendRectangle(p0: PointF, p1: PointF, p2: PointF, p3: PointF) {}
+ override fun clip(windingRule: Path.FillType) {}
+ override fun moveTo(x: Float, y: Float) {}
+ override fun lineTo(x: Float, y: Float) {}
+ override fun curveTo(x1: Float, y1: Float, x2: Float, y2: Float, x3: Float, y3: Float) {}
+ override fun getCurrentPoint(): PointF = PointF(0f, 0f)
+ override fun closePath() {}
+ override fun endPath() {}
+ override fun strokePath() {}
+ override fun fillPath(windingRule: Path.FillType) {}
+ override fun fillAndStrokePath(windingRule: Path.FillType) {}
+ override fun shadingFill(shadingName: COSName) {}
+ }
+ engine.processPage(page)
+ return found
+ }
+}