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.

Edit only the selected text, in the PDF's own font; fill form fields on the page (#68)

chethan616450465b20c6e
diff --git a/app/src/main/java/com/chethan616/clearpdf/data/repository/OnboardingManager.kt b/app/src/main/java/com/chethan616/clearpdf/data/repository/OnboardingManager.kt
index 13adfc6..6d2b5c5 100644
--- a/app/src/main/java/com/chethan616/clearpdf/data/repository/OnboardingManager.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/data/repository/OnboardingManager.kt
@@ -23,6 +23,7 @@ object OnboardingManager {
private const val KEY_EDIT_TEXT_TOUR_SEEN = "edit_text_tour_seen"
private const val KEY_RECENTS_MENU_TOUR_SEEN = "recents_menu_tour_seen"
private const val KEY_GLASS_SETTINGS_TOUR_SEEN = "glass_settings_tour_seen"
+ private const val KEY_FORM_FILL_TOUR_SEEN = "form_fill_tour_seen"
private fun prefs(context: Context): SharedPreferences =
context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
@@ -80,6 +81,9 @@ object OnboardingManager {
fun hasSeenGlassSettingsTour(context: Context): Boolean = prefs(context).getBoolean(KEY_GLASS_SETTINGS_TOUR_SEEN, false)
fun markGlassSettingsTourSeen(context: Context) = prefs(context).edit().putBoolean(KEY_GLASS_SETTINGS_TOUR_SEEN, true).apply()
+ fun hasSeenFormFillTour(context: Context): Boolean = prefs(context).getBoolean(KEY_FORM_FILL_TOUR_SEEN, false)
+ fun markFormFillTourSeen(context: Context) = prefs(context).edit().putBoolean(KEY_FORM_FILL_TOUR_SEEN, true).apply()
+
fun resetOnboarding(context: Context) =
prefs(context).edit()
.putBoolean(KEY_COMPLETED, false)
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 0da82ae..a50c5a2 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
@@ -126,6 +126,19 @@ internal fun PdfContinuousPage(
bitmap: Bitmap?,
darkPageAppearance: Boolean = false,
marks: MutableList<PdfMarkup>,
+ /** Exact renders of this page's in-place text edits, by markup id (see PdfTextEditPreview). */
+ textEditPatches: Map<Long, TextEditPatch> = emptyMap(),
+ /**
+ * The PDF's own fillable boxes on this page (#68) and the values filled so far, by field name.
+ * In Edit mode ([formEditing]) the boxes are outlined and a tap fills them in place.
+ */
+ formWidgets: List<com.kyant.pdfcore.form.PdfFormWidget> = emptyList(),
+ formValues: Map<String, String> = emptyMap(),
+ formEditing: Boolean = false,
+ focusedFormKey: String? = null,
+ onTapFormWidget: (com.kyant.pdfcore.form.PdfFormWidget) -> Unit = {},
+ onFormTextChange: (com.kyant.pdfcore.form.PdfFormWidget, String) -> Unit = { _, _ -> },
+ onFormImeNext: (com.kyant.pdfcore.form.PdfFormWidget) -> Unit = {},
ocrBlocks: List<OcrTextBlock>,
findMatches: List<FindMatch>,
currentMatchIndex: Int,
@@ -170,6 +183,9 @@ internal fun PdfContinuousPage(
val latestSelectedMarkupIndex by rememberUpdatedState(selectedMarkupIndex)
val latestSelectedMarkupIndices by rememberUpdatedState(selectedMarkupIndices)
val latestOcrBlocks by rememberUpdatedState(ocrBlocks)
+ val latestFormWidgets by rememberUpdatedState(formWidgets)
+ val latestFormEditing by rememberUpdatedState(formEditing)
+ val latestOnTapFormWidget by rememberUpdatedState(onTapFormWidget)
DisposableEffect(page, textSelection) { onDispose { textSelection.unregisterPage(page, null) } }
// Accessibility: expose the page's extracted text to TalkBack, plus a "select page text" action.
val selectPageLabel = stringResource(R.string.selection_select_page_text)
@@ -255,6 +271,31 @@ internal fun PdfContinuousPage(
Canvas(Modifier.matchParentSize()) {
val frame = Rect(0f, 0f, size.width, size.height)
+ // Edited lines first, so highlights and other markups still draw on top: the band of
+ // the page around each edit, rendered from the edited PDF itself.
+ marks.forEach { m ->
+ if (m !is PdfMarkup.TextEditMarkup) return@forEach
+ val patch = textEditPatches[m.id]?.takeIf { it.text == m.text && !it.bitmap.isRecycled } ?: return@forEach
+ val b = patch.band
+ val left = (b.left * size.width).roundToInt()
+ val top = (b.top * size.height).roundToInt()
+ drawImage(
+ image = patch.bitmap.asImageBitmap(),
+ srcOffset = IntOffset.Zero,
+ srcSize = androidx.compose.ui.unit.IntSize(patch.bitmap.width, patch.bitmap.height),
+ dstOffset = IntOffset(left, top),
+ dstSize = androidx.compose.ui.unit.IntSize(
+ ((b.right * size.width).roundToInt() - left).coerceAtLeast(1),
+ ((b.bottom * size.height).roundToInt() - top).coerceAtLeast(1)
+ ),
+ filterQuality = androidx.compose.ui.graphics.FilterQuality.High,
+ colorFilter = if (darkPageAppearance) InvertColorFilter else null
+ )
+ }
+
+ // The PDF's own form boxes: filled values in place, and the Edit-mode outline.
+ if (formWidgets.isNotEmpty()) drawFormWidgets(formWidgets, formValues, formEditing, focusedFormKey, darkPageAppearance)
+
// Text selection highlight — the platform selection colour, one band per line fragment.
// Drawn inside the zoom layer so it scales with the page, exactly like the glyphs.
textSelection.pageRange(page)?.let { (from, to) ->
@@ -298,8 +339,10 @@ internal fun PdfContinuousPage(
cap = StrokeCap.Round
)
}
- is PdfMarkup.TextEditMarkup -> {
- // Preview of an in-place edit: the old line hidden under the page's own
+ // Drawn inside its form box by drawFormWidgets.
+ is PdfMarkup.FormValueMarkup -> Unit
+ is PdfMarkup.TextEditMarkup -> if (textEditPatches[markup.id]?.text != markup.text) {
+ // 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
@@ -509,6 +552,26 @@ internal fun PdfContinuousPage(
val selBounds = sel?.movableBounds()
if (selBounds != null && selBounds.inflate(30f).contains(down.position)) return@awaitEachGesture
+ // Edit mode: a tap on one of the PDF's own form boxes fills it (#68).
+ if (latestFormEditing && latestFormWidgets.isNotEmpty()) {
+ val nx = down.position.x / size.width.toFloat()
+ val ny = down.position.y / size.height.toFloat()
+ val slop = 6f / size.width.toFloat()
+ val box = latestFormWidgets.lastOrNull { w ->
+ !w.readOnly && nx >= w.left - slop && nx <= w.right + slop && ny >= w.top - slop && ny <= w.bottom + slop
+ }
+ if (box != null) {
+ val up = waitForUpOrCancellation()
+ if (up != null) {
+ up.consume()
+ latestOnTapFormWidget(box)
+ onShowControls()
+ onInteraction()
+ }
+ return@awaitEachGesture
+ }
+ }
+
val frame = Rect(0f, 0f, size.width.toFloat(), size.height.toFloat())
val idx = marks.indexOfLast { it.hitTest(down.position, currentBlocks, frame) }
if (idx >= 0) {
@@ -786,6 +849,22 @@ internal fun PdfContinuousPage(
}
}
+ // Typing into the PDF's own text field, right where it is printed (#68).
+ if (focusedFormKey != null) {
+ formWidgets.firstOrNull { it.key == focusedFormKey && it.type == com.kyant.pdfcore.form.PdfFormWidget.Type.TEXT }?.let { w ->
+ pageCanvasSizes[page]?.takeIf { it.width > 0f && it.height > 0f }?.let { canvas ->
+ PdfFormInlineEditor(
+ widget = w,
+ value = formValues[w.fieldName] ?: w.value,
+ canvas = canvas,
+ dark = darkPageAppearance,
+ onValueChange = { onFormTextChange(w, it) },
+ onImeNext = { onFormImeNext(w) }
+ )
+ }
+ }
+ }
+
// An edited line of the page's own text: Edit reopens the editor, Delete restores the
// original line.
(marks.getOrNull(selectedMarkupIndex) as? PdfMarkup.TextEditMarkup)?.let { te ->
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfFormFill.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfFormFill.kt
new file mode 100644
index 0000000..d8af612
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfFormFill.kt
@@ -0,0 +1,369 @@
+package com.chethan616.clearpdf.ui.screen
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.border
+import androidx.compose.foundation.horizontalScroll
+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.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.offset
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.rememberScrollState
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.foundation.text.BasicText
+import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.rounded.KeyboardArrowDown
+import androidx.compose.material.icons.rounded.KeyboardArrowUp
+import androidx.compose.material3.Icon
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+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.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.Path
+import androidx.compose.ui.graphics.SolidColor
+import androidx.compose.ui.graphics.StrokeCap
+import androidx.compose.ui.graphics.StrokeJoin
+import androidx.compose.ui.graphics.drawscope.DrawScope
+import androidx.compose.ui.graphics.drawscope.Stroke
+import androidx.compose.ui.graphics.drawscope.clipRect
+import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
+import androidx.compose.ui.graphics.nativeCanvas
+import androidx.compose.ui.graphics.toArgb
+import androidx.compose.ui.platform.LocalDensity
+import androidx.compose.ui.text.TextRange
+import androidx.compose.ui.text.TextStyle
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.text.input.TextFieldValue
+import androidx.compose.ui.text.input.VisualTransformation
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.IntOffset
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.sp
+import com.chethan616.clearpdf.R
+import com.chethan616.clearpdf.ui.components.LiquidButton
+import com.chethan616.clearpdf.ui.components.LiquidIconButton
+import com.chethan616.clearpdf.ui.components.viewerGlass
+import com.kyant.backdrop.backdrops.LayerBackdrop
+import com.kyant.pdfcore.form.PdfFormWidget
+import kotlinx.coroutines.delay
+import kotlin.math.min
+import kotlin.math.roundToInt
+
+/** The tint form boxes wear in Edit mode: the system's "fillable" blue. */
+internal val FormTint = Color(0xFF0A84FF)
+
+/** A widget's box in this page's content px. */
+internal fun PdfFormWidget.rectIn(size: Size): Rect =
+ Rect(left * size.width, top * size.height, right * size.width, bottom * size.height)
+
+/** One PDF point in this page's content px. */
+internal fun PdfFormWidget.ptPx(size: Size): Float = size.height / pageHeightPt.coerceAtLeast(1f)
+
+/**
+ * The value's text size in px: the field's own (DA) size, or, for an auto-sized field, the size
+ * the saved form will use (PDFBox's rule): 12 pt when multi-line, else the largest size whose cap
+ * height plus descent fills the box inside its 2 pt padding, and whose [text] still fits across.
+ */
+internal fun PdfFormWidget.textPx(size: Size, text: String): Float {
+ if (fontSizeNorm > 0f) return fontSizeNorm * size.height
+ val pt = ptPx(size)
+ if (multiline) return 12f * pt
+ val r = rectIn(size)
+ val byHeight = (r.height - 4f * pt).coerceAtLeast(1f) / 0.925f
+ if (text.isEmpty()) return byHeight
+ val em = AutoSizePaint.measureText(text) / AutoSizePaint.textSize
+ val byWidth = if (em > 0f) (r.width - 4f * pt).coerceAtLeast(1f) / em else byHeight
+ return min(byHeight, byWidth)
+}
+
+private val AutoSizePaint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = 100f
+ typeface = android.graphics.Typeface.SANS_SERIF
+}
+
+private fun invert(c: Color) = Color(1f - c.red, 1f - c.green, 1f - c.blue, c.alpha)
+
+/**
+ * Draws this page's form boxes: in Edit mode a soft blue wash and rim on every box (stronger on the
+ * one being filled), and every value filled in this session inside its box, in the field's own
+ * size, alignment and colour, so the page shows exactly what will be saved. [dark] is the dark
+ * reader, which inverts the page, so paper and ink invert with it.
+ */
+internal fun DrawScope.drawFormWidgets(
+ widgets: List<PdfFormWidget>,
+ values: Map<String, String>,
+ editing: Boolean,
+ focusedKey: String?,
+ dark: Boolean
+) {
+ val paper = if (dark) Color.Black else Color.White
+ widgets.forEach { w ->
+ val r = w.rectIn(size)
+ val focused = w.key == focusedKey
+ val ink = Color(w.textArgb).let { if (dark) invert(it) else it }
+ val v = values[w.fieldName]
+ // The live editor draws the focused text box itself.
+ if (v != null && !(focused && w.type == PdfFormWidget.Type.TEXT)) drawFormValue(w, v, r, paper, ink)
+ if (editing || focused) {
+ val cr = CornerRadius(min(r.width, r.height) * 0.14f)
+ drawRoundRect(FormTint.copy(alpha = if (focused) 0.16f else 0.09f), r.topLeft, r.size, cr)
+ drawRoundRect(
+ FormTint.copy(alpha = if (focused) 0.95f else 0.5f), r.topLeft, r.size, cr,
+ style = Stroke(if (focused) 2.4f else 1.3f)
+ )
+ }
+ }
+}
+
+private fun DrawScope.drawFormValue(w: PdfFormWidget, v: String, r: Rect, paper: Color, ink: Color) {
+ when (w.type) {
+ PdfFormWidget.Type.CHECKBOX -> {
+ val inset = r.minDimension * 0.14f
+ drawRect(paper, Offset(r.left + inset, r.top + inset), Size(r.width - inset * 2, r.height - inset * 2))
+ if (v == "true") {
+ val s = r.minDimension
+ val ox = r.center.x - s / 2f
+ val oy = r.center.y - s / 2f
+ val check = Path().apply {
+ moveTo(ox + s * 0.24f, oy + s * 0.53f)
+ lineTo(ox + s * 0.43f, oy + s * 0.71f)
+ lineTo(ox + s * 0.77f, oy + s * 0.30f)
+ }
+ drawPath(check, ink, style = Stroke(s * 0.11f, cap = StrokeCap.Round, join = StrokeJoin.Round))
+ }
+ }
+ PdfFormWidget.Type.RADIO -> {
+ val radius = r.minDimension / 2f
+ drawCircle(paper, radius * 0.74f, r.center)
+ if (v == w.onValue) drawCircle(ink, radius * 0.38f, r.center)
+ }
+ PdfFormWidget.Type.TEXT, PdfFormWidget.Type.CHOICE -> {
+ val inset = min(r.height * 0.06f, 3f)
+ drawRect(paper, Offset(r.left + inset, r.top + inset), Size(r.width - inset * 2, r.height - inset * 2))
+ if (v.isEmpty()) return
+ val shown = if (w.password) "•".repeat(v.length) else v
+ val textPx = w.textPx(size, shown)
+ val pad = 2f * w.ptPx(size)
+ clipRect(r.left, r.top, r.right, r.bottom) {
+ drawIntoCanvas { cv ->
+ val paint = android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = textPx
+ color = ink.toArgb()
+ typeface = android.graphics.Typeface.SANS_SERIF
+ }
+ val nc = cv.nativeCanvas
+ when {
+ w.comb && w.maxLength > 0 -> {
+ val cell = r.width / w.maxLength
+ val y = r.center.y + textPx * 0.35f
+ shown.take(w.maxLength).forEachIndexed { i, ch ->
+ val s = ch.toString()
+ nc.drawText(s, r.left + cell * i + (cell - paint.measureText(s)) / 2f, y, paint)
+ }
+ }
+ w.multiline -> {
+ val maxW = r.width - pad * 2
+ var y = r.top + pad + textPx
+ for (line in wrap(shown, paint, maxW)) {
+ if (y > r.bottom + textPx) break
+ nc.drawText(line, alignedX(w.alignment, r, pad, paint.measureText(line)), y, paint)
+ y += textPx * 1.16f
+ }
+ }
+ else -> {
+ val y = r.center.y + textPx * 0.35f
+ nc.drawText(shown, alignedX(w.alignment, r, pad, paint.measureText(shown)), y, paint)
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+private fun alignedX(alignment: Int, r: Rect, pad: Float, width: Float): Float = when (alignment) {
+ 1 -> r.center.x - width / 2f
+ 2 -> r.right - pad - width
+ else -> r.left + pad
+}
+
+private fun wrap(text: String, paint: android.graphics.Paint, maxW: Float): List<String> {
+ val out = ArrayList<String>()
+ for (para in text.split('\n')) {
+ var line = ""
+ for (word in para.split(' ')) {
+ val candidate = if (line.isEmpty()) word else "$line $word"
+ if (paint.measureText(candidate) <= maxW || line.isEmpty()) line = candidate
+ else { out += line; line = word }
+ }
+ out += line
+ }
+ return out
+}
+
+/**
+ * Typing straight into a text field on the page: a real text field laid exactly over the box, in
+ * the field's size, alignment and colour (and dot-masked for password fields), so what is typed is
+ * what the saved form shows. It lives inside the page's zoom layer, so it zooms with the page.
+ */
+@Composable
+internal fun PdfFormInlineEditor(
+ widget: PdfFormWidget,
+ value: String,
+ canvas: Size,
+ dark: Boolean,
+ onValueChange: (String) -> Unit,
+ onImeNext: () -> Unit
+) {
+ val density = LocalDensity.current
+ val r = widget.rectIn(canvas)
+ if (r.width <= 1f || r.height <= 1f) return
+ val focus = remember { FocusRequester() }
+ var field by remember(widget.key) { mutableStateOf(TextFieldValue(value, TextRange(value.length))) }
+ // Auto-sized fields shrink as the text grows, exactly as the saved form will.
+ val textPx = widget.textPx(canvas, if (widget.password) "•".repeat(field.text.length) else field.text)
+ LaunchedEffect(value) {
+ if (value != field.text) field = TextFieldValue(value, TextRange(value.length))
+ }
+ LaunchedEffect(widget.key) { delay(80); runCatching { focus.requestFocus() } }
+ val paper = if (dark) Color.Black else Color.White
+ val ink = Color(widget.textArgb).let { if (dark) invert(it) else it }
+ val pad = with(density) { (2f * widget.ptPx(canvas)).toDp() }
+ val comb = widget.comb && widget.maxLength > 0
+ val style = TextStyle(
+ color = ink,
+ fontSize = with(density) { textPx.toSp() },
+ textAlign = when { comb -> TextAlign.Start; widget.alignment == 1 -> TextAlign.Center; widget.alignment == 2 -> TextAlign.End; else -> TextAlign.Start },
+ letterSpacing = if (comb) with(density) { (r.width / widget.maxLength - textPx * 0.56f).coerceAtLeast(0f).toSp() } else TextStyle.Default.letterSpacing
+ )
+ BasicTextField(
+ value = field,
+ onValueChange = { next ->
+ val text = if (widget.maxLength > 0) next.text.take(widget.maxLength) else next.text
+ field = if (text == next.text) next else next.copy(text = text, selection = TextRange(text.length))
+ if (text != value) onValueChange(text)
+ },
+ singleLine = !widget.multiline,
+ textStyle = style,
+ cursorBrush = SolidColor(FormTint),
+ visualTransformation = if (widget.password) PasswordVisualTransformation() else VisualTransformation.None,
+ keyboardOptions = KeyboardOptions(imeAction = if (widget.multiline) ImeAction.Default else ImeAction.Next),
+ keyboardActions = KeyboardActions(onNext = { onImeNext() }),
+ modifier = Modifier
+ .offset { IntOffset(r.left.roundToInt(), r.top.roundToInt()) }
+ .size(with(density) { r.width.toDp() }, with(density) { r.height.toDp() })
+ .background(paper, RoundedCornerShape(3.dp))
+ .border(1.5.dp, FormTint, RoundedCornerShape(3.dp))
+ .padding(horizontal = pad)
+ .focusRequester(focus),
+ decorationBox = { inner ->
+ Box(
+ Modifier.fillMaxSize(),
+ contentAlignment = if (widget.multiline) Alignment.TopStart else Alignment.CenterStart
+ ) {
+ Box(Modifier.fillMaxWidth()) { inner() }
+ }
+ }
+ )
+}
+
+/** A field's name as people read it: "applicant.first_name" → "first name". */
+internal fun humanFieldName(name: String): String =
+ name.substringAfterLast('.')
+ .replace('_', ' ')
+ .replace(Regex("([a-z])([A-Z])"), "$1 $2")
+ .replace(Regex("\\[\\d+]"), "")
+ .trim()
+ .ifEmpty { name }
+
+/**
+ * The iOS-style form accessory, floating above the keyboard: previous / next field, the field's
+ * name, Done, and, for a choice field (which has no keyboard), its options as glass chips.
+ */
+@Composable
+internal fun PdfFormAccessoryBar(
+ widget: PdfFormWidget,
+ value: String,
+ backdrop: LayerBackdrop,
+ ink: Color,
+ glass: Color,
+ canPrevious: Boolean,
+ canNext: Boolean,
+ onPrevious: () -> Unit,
+ onNext: () -> Unit,
+ onDone: () -> Unit,
+ onPick: (String) -> Unit,
+ modifier: Modifier = Modifier
+) {
+ Column(
+ modifier
+ .fillMaxWidth()
+ .viewerGlass(backdrop, glass, shape = { RoundedCornerShape(26.dp) })
+ .padding(horizontal = 8.dp, vertical = 8.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ LiquidIconButton(
+ onClick = onPrevious, backdrop = backdrop, isInteractive = canPrevious,
+ surfaceColor = glass, modifier = Modifier.size(38.dp)
+ ) { Icon(Icons.Rounded.KeyboardArrowUp, androidx.compose.ui.res.stringResource(R.string.form_fill_previous), Modifier.size(22.dp), ink.copy(if (canPrevious) 1f else 0.35f)) }
+ LiquidIconButton(
+ onClick = onNext, backdrop = backdrop, isInteractive = canNext,
+ surfaceColor = glass, modifier = Modifier.size(38.dp)
+ ) { Icon(Icons.Rounded.KeyboardArrowDown, androidx.compose.ui.res.stringResource(R.string.form_fill_next), Modifier.size(22.dp), ink.copy(if (canNext) 1f else 0.35f)) }
+ BasicText(
+ humanFieldName(widget.fieldName),
+ style = TextStyle(ink.copy(0.75f), 13.sp, FontWeight.Medium),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis,
+ modifier = Modifier.weight(1f).padding(horizontal = 4.dp)
+ )
+ LiquidButton(onClick = onDone, backdrop = backdrop, tint = FormTint, modifier = Modifier.padding(end = 2.dp)) {
+ BasicText(androidx.compose.ui.res.stringResource(R.string.viewer_done), style = TextStyle(Color.White, 14.sp, FontWeight.SemiBold))
+ }
+ }
+ if (widget.type == PdfFormWidget.Type.CHOICE && widget.options.isNotEmpty()) {
+ Row(
+ Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()).padding(horizontal = 2.dp),
+ horizontalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ widget.options.forEach { option ->
+ val selected = option == value
+ LiquidButton(
+ onClick = { onPick(option) },
+ backdrop = backdrop,
+ tint = if (selected) FormTint else Color.Unspecified,
+ surfaceColor = if (selected) Color.Unspecified else glass
+ ) {
+ BasicText(
+ option,
+ style = TextStyle(if (selected) Color.White else ink, 14.sp, if (selected) FontWeight.SemiBold else FontWeight.Medium),
+ maxLines = 1
+ )
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerDialogs.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerDialogs.kt
index a135362..7004198 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerDialogs.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerDialogs.kt
@@ -312,6 +312,7 @@ internal fun AnnotationEditorDialog(
internal fun TextEditDialog(
initialText: String,
original: String,
+ selectionOnly: Boolean = false,
backdrop: LayerBackdrop,
canRevert: Boolean,
onDismiss: () -> Unit,
@@ -333,13 +334,18 @@ internal fun TextEditDialog(
GlassDialogAction(stringResource(R.string.viewer_done), { onSave(text) }, primary = true)
}
) {
- BasicText(stringResource(R.string.text_edit_hint), style = TextStyle(glassDialogInkSoft(), 12.sp, lineHeight = 16.sp))
+ BasicText(
+ stringResource(if (selectionOnly) R.string.text_edit_hint_selection else R.string.text_edit_hint),
+ style = TextStyle(glassDialogInkSoft(), 12.sp, lineHeight = 16.sp)
+ )
Spacer(Modifier.height(10.dp))
+ // Wraps instead of scrolling sideways, so a long line is readable and editable in full;
+ // capped so the dialog never outgrows the screen (then it scrolls vertically).
GlassDialogField(
value = text,
onValueChange = { text = it.replace('\n', ' ') },
- modifier = Modifier.fillMaxWidth(),
- singleLine = true,
+ modifier = Modifier.fillMaxWidth().heightIn(max = 168.dp),
+ singleLine = false,
focusRequester = focus,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { onSave(text) })
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt
index df157fb..c53d716 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/PdfViewerInternals.kt
@@ -131,7 +131,19 @@ internal sealed class PdfMarkup {
val bold: Boolean,
val italic: Boolean,
val serif: Boolean,
- val mono: Boolean
+ val mono: Boolean,
+ /** The original line's per-character x bounds (normalized), so only what changed is rewritten. */
+ val charLefts: FloatArray = FloatArray(0),
+ val charRights: FloatArray = FloatArray(0)
+ ) : PdfMarkup()
+
+ /**
+ * A value filled into one of the PDF's own form fields (#68), kept on the page of the box it
+ * was filled in. Not drawn as a markup: the page draws the value inside the field itself.
+ */
+ data class FormValueMarkup(
+ val fieldName: String,
+ val value: String
) : PdfMarkup()
/** Sticky note. [anchor] is the content-space top-left of the icon. */
@@ -175,6 +187,7 @@ internal sealed class PdfMarkup {
r.contains(p)
}
is TextEditMarkup -> rect.inflate(8f).contains(p)
+ is FormValueMarkup -> false
}
}
@@ -705,19 +718,9 @@ internal fun buildExportOverlays(
}
}
is PdfMarkup.TextEditMarkup -> {
- if (markup.text != markup.original) {
- list.add(
- ExportOverlay.TextReplace(
- left = markup.rect.left / frame.width.coerceAtLeast(1f),
- top = markup.rect.top / frame.height.coerceAtLeast(1f),
- right = markup.rect.right / frame.width.coerceAtLeast(1f),
- bottom = markup.rect.bottom / frame.height.coerceAtLeast(1f),
- text = markup.text,
- backgroundArgb = markup.background.toArgb()
- )
- )
- }
+ markup.toTextReplace(frame.width, frame.height)?.let { list.add(it) }
}
+ is PdfMarkup.FormValueMarkup -> list.add(ExportOverlay.FormValue(markup.fieldName, markup.value))
is PdfMarkup.NoteMarkup -> {
list.add(
ExportOverlay.NoteStamp(
@@ -755,7 +758,9 @@ internal fun recolorSignatureBitmap(source: Bitmap, colorArgb: Int): Bitmap {
internal data class TextEditTarget(
val page: Int,
val block: com.chethan616.clearpdf.ui.viewmodel.OcrTextBlock?,
- val markupId: Long?
+ val markupId: Long?,
+ /** The selected characters of the ORIGINAL line, end exclusive; null edits the whole line. */
+ val selection: IntRange? = null
)
/**
@@ -785,7 +790,107 @@ internal fun textEditMarkupFor(
bold = style.bold,
italic = style.italic,
serif = style.serif,
- mono = style.mono
+ mono = style.mono,
+ charLefts = block.charLefts,
+ charRights = block.charRights
+ )
+}
+
+/** Where [current] differs from [original]: (start, end in original, end in current), end exclusive. */
+internal fun textDiff(original: String, current: String): Triple<Int, Int, Int> {
+ val max = minOf(original.length, current.length)
+ var p = 0
+ while (p < max && original[p] == current[p]) p++
+ var s = 0
+ while (s < max - p && original[original.length - 1 - s] == current[current.length - 1 - s]) s++
+ return Triple(p, original.length - s, current.length - s)
+}
+
+/**
+ * The part of [current] (a line's text after earlier edits) that a selection of
+ * [selStart] until [selEnd] in [original] covers. A selection touching an earlier change grows to
+ * include all of it, so the editor never shows half of a previous edit.
+ */
+internal fun selectionInCurrent(original: String, current: String, selStart: Int, selEnd: Int): IntRange {
+ val (p, oEnd, cEnd) = textDiff(original, current)
+ val delta = current.length - original.length
+ val r = when {
+ selEnd <= p -> selStart until selEnd
+ selStart >= oEnd -> (selStart + delta) until (selEnd + delta)
+ else -> minOf(selStart, p) until maxOf(if (selEnd > oEnd) selEnd + delta else cEnd, cEnd)
+ }
+ val a = r.first.coerceIn(0, current.length)
+ val b = (r.last + 1).coerceIn(a, current.length)
+ return a until b
+}
+
+/**
+ * The save-path form of an in-place edit: only the words that changed are rewritten (the rest of
+ * the line keeps its original glyphs, moved by the change in width), falling back to the whole
+ * line when there is no per-character geometry. Null when nothing changed.
+ */
+internal fun PdfMarkup.TextEditMarkup.toTextReplace(frameW: Float, frameH: Float): ExportOverlay.TextReplace? {
+ if (text == original) return null
+ val w = frameW.coerceAtLeast(1f)
+ val h = frameH.coerceAtLeast(1f)
+ val lineL = rect.left / w
+ val lineT = rect.top / h
+ val lineR = rect.right / w
+ val lineB = rect.bottom / h
+ val bg = background.toArgb()
+ val whole = ExportOverlay.TextReplace(lineL, lineT, lineR, lineB, text, bg)
+ val n = original.length
+ if (n == 0 || charLefts.size != n || charRights.size != n) return whole
+
+ val (p, oEnd, cEnd) = textDiff(original, text)
+ // Grow to whole words: every edit box then holds real glyphs to anchor on, and unchanged
+ // letters of a touched word are re-drawn from their own bytes, identical to before.
+ var a = p
+ var oe = oEnd
+ var ce = cEnd
+ while (a > 0 && !original[a - 1].isWhitespace()) a--
+ while (oe < n && !original[oe].isWhitespace()) { oe++; ce++ }
+ if (original.substring(a, oe).isBlank()) {
+ // Only spaces changed (or a pure insertion between words): anchor on a neighbouring word.
+ if (a > 0) {
+ while (a > 0 && original[a - 1].isWhitespace()) a--
+ while (a > 0 && !original[a - 1].isWhitespace()) a--
+ } else {
+ while (oe < n && original[oe].isWhitespace()) { oe++; ce++ }
+ while (oe < n && !original[oe].isWhitespace()) { oe++; ce++ }
+ }
+ }
+ if (a >= oe || ce < a || ce > text.length) return whole
+ if (a == 0 && oe == n) return whole
+ return ExportOverlay.TextReplace(
+ left = charLefts[a],
+ top = lineT,
+ right = charRights[oe - 1],
+ bottom = lineB,
+ text = text.substring(a, ce),
+ backgroundArgb = bg,
+ lineLeft = lineL,
+ lineTop = lineT,
+ lineRight = lineR,
+ lineBottom = lineB
+ )
+}
+
+/**
+ * An exact preview of a page's text edits: [bitmap] is the edited page rendered by the PDF engine
+ * over the normalized horizontal [band] around the line, valid while the markup's text is [text].
+ */
+internal class TextEditPatch(val text: String, val band: android.graphics.RectF, val bitmap: Bitmap)
+
+/** The band an edited line's preview covers: full page width, the line plus room for ascenders. */
+internal fun PdfMarkup.TextEditMarkup.previewBand(canvasH: Float): android.graphics.RectF {
+ val h = canvasH.coerceAtLeast(1f)
+ val pad = rect.height * 0.45f
+ return android.graphics.RectF(
+ 0f,
+ ((rect.top - pad) / h).coerceIn(0f, 1f),
+ 1f,
+ ((rect.bottom + pad) / h).coerceIn(0f, 1f)
)
}
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 27d7e7b..73ef74e 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
@@ -67,6 +67,7 @@ import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.runtime.snapshotFlow
import kotlinx.coroutines.flow.debounce
+import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChanged
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
@@ -302,6 +303,39 @@ fun PdfViewerScreen(
fun getPageMarks(page: Int): MutableList<PdfMarkup> =
annotationsByPage.getOrPut(page) { mutableStateListOf() }
+ // Exact previews of in-place text edits: each edited page is edited for real and rendered by
+ // the same engine as the page (PdfTextEditPreview), and the band around every edited line is
+ // laid over the page. Until a band arrives the page shows the quick system-font preview.
+ val textEditPatches = remember { mutableStateMapOf<Long, TextEditPatch>() }
+ val textEditDocUri = state.document?.uri
+ LaunchedEffect(textEditDocUri) {
+ val uri = textEditDocUri ?: return@LaunchedEffect
+ val rendered = HashMap<Int, List<Pair<Long, String>>>()
+ snapshotFlow {
+ annotationsByPage.entries.associate { (page, marks) ->
+ page to marks.filterIsInstance<PdfMarkup.TextEditMarkup>().map { it.id to it.text }
+ }.filterValues { it.isNotEmpty() }
+ }.distinctUntilChanged().collectLatest { byPage ->
+ delay(80)
+ for ((page, signature) in byPage) {
+ if (rendered[page] == signature) continue
+ val canvas = pageCanvasSizes[page] ?: continue
+ if (canvas.width <= 0f || canvas.height <= 0f) continue
+ val marks = annotationsByPage[page]?.filterIsInstance<PdfMarkup.TextEditMarkup>().orEmpty()
+ val edits = marks.mapNotNull { it.toTextReplace(canvas.width, canvas.height)?.toPdfTextEdit() }
+ val bands = marks.map { it.previewBand(canvas.height) }
+ val widthPx = (canvas.width * 2f).toInt().coerceIn(800, 3200)
+ val bitmaps = withContext(Dispatchers.IO) {
+ com.kyant.pdfcore.text.PdfTextEditPreview.render(context, uri, page, edits, bands, widthPx)
+ }
+ marks.forEachIndexed { i, m ->
+ bitmaps.getOrNull(i)?.let { textEditPatches[m.id] = TextEditPatch(m.text, bands[i], it) }
+ }
+ rendered[page] = signature
+ }
+ }
+ }
+
// ── Unsaved-edit tracking ──────────────────────────────────────────────
// Markups live here (not in the ViewModel), so "dirty" is: the current markups differ from what
// was last exported. PdfMarkup variants are data classes, so a structural compare of a per-page
@@ -432,6 +466,34 @@ fun PdfViewerScreen(
/** Record that [page] just gained a markup, so undo can find it again. */
fun recordEdit(page: Int) { undoStack.add(page) }
+ // ── Fill the PDF's own form fields in place (#68) ──
+ // In Edit mode the boxes are outlined on the page; a tap ticks a checkbox / radio, or focuses a
+ // text field (typed into right where it is printed) or a choice field (options in the bar).
+ // Each filled value is a FormValueMarkup, so undo, unsaved-changes, save and share all apply.
+ var focusedForm by remember { mutableStateOf<com.kyant.pdfcore.form.PdfFormWidget?>(null) }
+ val formValues by remember {
+ derivedStateOf {
+ annotationsByPage.values.flatMap { l -> l.filterIsInstance<PdfMarkup.FormValueMarkup>() }
+ .associate { it.fieldName to it.value }
+ }
+ }
+ fun formValueOf(w: com.kyant.pdfcore.form.PdfFormWidget): String = formValues[w.fieldName] ?: w.value
+ fun setFormValue(w: com.kyant.pdfcore.form.PdfFormWidget, value: String) {
+ var found = false
+ annotationsByPage.values.forEach { list ->
+ val i = list.indexOfFirst { it is PdfMarkup.FormValueMarkup && it.fieldName == w.fieldName }
+ if (i >= 0) {
+ found = true
+ if (value == w.value) list.removeAt(i) else list[i] = PdfMarkup.FormValueMarkup(w.fieldName, value)
+ }
+ }
+ if (!found && value != w.value) {
+ getPageMarks(w.pageIndex).add(PdfMarkup.FormValueMarkup(w.fieldName, value))
+ recordEdit(w.pageIndex)
+ }
+ }
+
+
/**
* Remove the most recently added markup, wherever it lives. Entries can go stale — the eraser
* and the shape editor delete marks without touching the stack — so pop past any page that has
@@ -753,6 +815,42 @@ fun PdfViewerScreen(
// there is no feedback loop.
val contentBackdrop = rememberLayerBackdrop()
+ // Form filling (#68): which boxes take part, in reading order, and how a tap fills one.
+ val formEditing = editorToolsOpen && state.formWidgetsByPage.isNotEmpty()
+ val formOrder = remember(state.formWidgetsByPage) {
+ state.formWidgetsByPage.values.flatten()
+ .filter { !it.readOnly && (it.type == com.kyant.pdfcore.form.PdfFormWidget.Type.TEXT || it.type == com.kyant.pdfcore.form.PdfFormWidget.Type.CHOICE) }
+ .sortedWith(compareBy({ it.pageIndex }, { it.top }, { it.left }))
+ }
+ var showFormTour by remember { mutableStateOf(!OnboardingManager.hasSeenFormFillTour(context)) }
+ val keyboard = androidx.compose.ui.platform.LocalSoftwareKeyboardController.current
+ LaunchedEffect(formEditing) { if (!formEditing) focusedForm = null }
+ LaunchedEffect(state.document?.uri) { focusedForm = null }
+ // Bring the focused box into the top of the viewport, clear of the keyboard and the bar.
+ LaunchedEffect(focusedForm?.key) {
+ val w = focusedForm ?: return@LaunchedEffect
+ val canvas = pageCanvasSizes[w.pageIndex]
+ val viewport = listState.layoutInfo.viewportSize.height
+ val offset = if (canvas != null) (w.top * canvas.height - viewport * 0.22f).toInt() else 0
+ runCatching { listState.animateScrollToItem(w.pageIndex, offset.coerceAtLeast(0)) }
+ }
+ val onTapFormWidget: (com.kyant.pdfcore.form.PdfFormWidget) -> Unit = { w ->
+ if (showFormTour) { showFormTour = false; OnboardingManager.markFormFillTourSeen(context) }
+ when (w.type) {
+ com.kyant.pdfcore.form.PdfFormWidget.Type.TEXT, com.kyant.pdfcore.form.PdfFormWidget.Type.CHOICE -> focusedForm = w
+ com.kyant.pdfcore.form.PdfFormWidget.Type.CHECKBOX -> {
+ focusedForm = null
+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.SegmentTick)
+ setFormValue(w, if (formValueOf(w) == "true") "false" else "true")
+ }
+ com.kyant.pdfcore.form.PdfFormWidget.Type.RADIO -> {
+ focusedForm = null
+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.SegmentTick)
+ setFormValue(w, w.onValue)
+ }
+ }
+ }
+
// ── Adaptive chrome contrast ────────────────────────────────────────────
// The chrome glass floats over the page, which may be a bright white note or a
// dark scan. Sample the current page's average luminance and flip the whole
@@ -1137,6 +1235,17 @@ fun PdfViewerScreen(
bitmap = state.pageBitmaps.getOrNull(page),
darkPageAppearance = darkPageAppearance,
marks = getPageMarks(page),
+ textEditPatches = textEditPatches,
+ formWidgets = state.formWidgetsByPage[page].orEmpty(),
+ formValues = formValues,
+ formEditing = formEditing,
+ focusedFormKey = focusedForm?.key,
+ onTapFormWidget = onTapFormWidget,
+ onFormTextChange = { w, v -> setFormValue(w, v) },
+ onFormImeNext = { w ->
+ val i = formOrder.indexOfFirst { it.key == w.key }
+ focusedForm = formOrder.getOrNull(i + 1)
+ },
ocrBlocks = state.ocrBlocksByPage[page].orEmpty(),
findMatches = state.findMatches,
currentMatchIndex = state.currentMatchIndex,
@@ -1828,8 +1937,15 @@ fun PdfViewerScreen(
val existing = getPageMarks(pg).firstOrNull {
it is PdfMarkup.TextEditMarkup && it.blockId == block.id
} as? PdfMarkup.TextEditMarkup
+ // Only what was selected is edited; the rest of the line stays exactly as it is.
+ val selected = textSelection.rangesByPage()[pg].orEmpty().filter { it.blockId == block.id }
+ val range = if (selected.isEmpty()) null else {
+ val a = selected.minOf { it.start }.coerceIn(0, block.text.length)
+ val b = selected.maxOf { it.end }.coerceIn(a, block.text.length)
+ (a until b).takeIf { b > a && (a > 0 || b < block.text.length) }
+ }
textSelection.clear()
- textEditTarget = TextEditTarget(pg, block, existing?.id)
+ textEditTarget = TextEditTarget(pg, block, existing?.id, range)
}
)
// A lambda, evaluated inside the toolbar: reading the selection here would recompose this
@@ -1864,6 +1980,48 @@ fun PdfViewerScreen(
luminanceAt = pageLuminanceAt,
appearanceKey = darkPageAppearance
)
+ // The form accessory: previous / next field, Done, and a choice field's options.
+ focusedForm?.let { w ->
+ BackHandler { focusedForm = null }
+ val i = formOrder.indexOfFirst { it.key == w.key }
+ val imeUp = androidx.compose.foundation.layout.WindowInsets.ime.getBottom(LocalDensity.current) > 0
+ PdfFormAccessoryBar(
+ widget = w,
+ value = formValueOf(w),
+ backdrop = contentBackdrop,
+ ink = panelFg,
+ glass = chromePanel,
+ canPrevious = i > 0,
+ canNext = i in 0 until formOrder.lastIndex,
+ onPrevious = { formOrder.getOrNull(i - 1)?.let { focusedForm = it } },
+ onNext = { formOrder.getOrNull(i + 1)?.let { focusedForm = it } },
+ onDone = { keyboard?.hide(); focusedForm = null },
+ onPick = { option ->
+ haptics.performHapticFeedback(androidx.compose.ui.hapticfeedback.HapticFeedbackType.SegmentTick)
+ setFormValue(w, option)
+ },
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .imePadding()
+ .navigationBarsPadding()
+ .padding(horizontal = 12.dp)
+ .padding(bottom = if (imeUp) 8.dp else 104.dp)
+ )
+ }
+ com.chethan616.clearpdf.ui.components.GlassGuideCallout(
+ visible = showFormTour && formEditing && focusedForm == null,
+ title = stringResource(R.string.tour_form_title),
+ message = stringResource(R.string.tour_form_message),
+ backdrop = contentBackdrop,
+ isLastStep = true,
+ onNext = { showFormTour = false; OnboardingManager.markFormFillTourSeen(context) },
+ onSkip = { showFormTour = false; OnboardingManager.markFormFillTourSeen(context) },
+ modifier = Modifier
+ .align(Alignment.TopCenter)
+ .statusBarsPadding()
+ .padding(start = 16.dp, end = 16.dp, top = 76.dp)
+ )
+
PdfCopiedToast(
trigger = copiedTick,
backdrop = contentBackdrop,
@@ -1895,11 +2053,16 @@ fun PdfViewerScreen(
list.firstOrNull { it is PdfMarkup.TextEditMarkup && it.id == id } as? PdfMarkup.TextEditMarkup
}
val original = existing?.original ?: target.block?.text.orEmpty()
+ val current = existing?.text ?: original
+ val segment = target.selection?.let { sel ->
+ selectionInCurrent(original, current, sel.first, sel.last + 1).takeIf { !it.isEmpty() }
+ }
TextEditDialog(
- initialText = existing?.text ?: original,
- original = original,
+ initialText = segment?.let { current.substring(it.first, it.last + 1) } ?: current,
+ original = segment?.let { current.substring(it.first, it.last + 1) } ?: original,
+ selectionOnly = segment != null,
backdrop = contentBackdrop,
- canRevert = existing != null,
+ canRevert = existing != null && segment == null,
onDismiss = { textEditTarget = null },
onRevert = {
list.removeAll { it is PdfMarkup.TextEditMarkup && it.id == existing?.id }
@@ -1907,7 +2070,8 @@ fun PdfViewerScreen(
selectedAnnoPage = null; selectedAnnoIndex = -1
textEditTarget = null
},
- onSave = { newText ->
+ onSave = { edited ->
+ val newText = segment?.let { current.replaceRange(it.first, it.last + 1, edited) } ?: edited
if (existing != null) {
val i = list.indexOf(existing)
if (i >= 0) {
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/WhatsNewScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/WhatsNewScreen.kt
index 8a332e1..6ecd7ac 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/WhatsNewScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/WhatsNewScreen.kt
@@ -19,6 +19,7 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.AutoAwesome
import androidx.compose.material.icons.rounded.BugReport
+import androidx.compose.material.icons.rounded.CheckBox
import androidx.compose.material.icons.rounded.EditNote
import androidx.compose.material.icons.rounded.IosShare
import androidx.compose.material.icons.rounded.TableChart
@@ -56,6 +57,7 @@ private class WhatsNewItem(val icon: ImageVector, val accent: Color, val title:
private val WhatsNewItems = listOf(
WhatsNewItem(Icons.Rounded.EditNote, LiquidGlassColors.Blue, R.string.whats_new_edit_title, R.string.whats_new_edit_desc),
+ WhatsNewItem(Icons.Rounded.CheckBox, LiquidGlassColors.Indigo, R.string.whats_new_forms_title, R.string.whats_new_forms_desc),
WhatsNewItem(Icons.Rounded.AutoAwesome, LiquidGlassColors.Teal, R.string.whats_new_glass_title, R.string.whats_new_glass_desc),
WhatsNewItem(Icons.Rounded.IosShare, LiquidGlassColors.Green, R.string.whats_new_share_title, R.string.whats_new_share_desc),
WhatsNewItem(Icons.Rounded.Vibration, LiquidGlassColors.Purple, R.string.whats_new_feel_title, R.string.whats_new_feel_desc),
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 d42612d..3b317a5 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
@@ -130,16 +130,28 @@ sealed class ExportOverlay {
/**
* An in-place edit of the page's own text: the glyphs inside the normalized box are removed
- * from the content stream and [text] is drawn in their font (see PdfTextEditor).
+ * from the content stream and [text] is drawn in their font (see PdfTextEditor). The line box
+ * lets a partial edit move the rest of its line by the change in width.
*/
+ /** A value typed or picked into the PDF's own form field, written into the form on save. */
+ data class FormValue(val fieldName: String, val value: String) : ExportOverlay()
+
data class TextReplace(
val left: Float,
val top: Float,
val right: Float,
val bottom: Float,
val text: String,
- val backgroundArgb: Int
- ) : ExportOverlay()
+ val backgroundArgb: Int,
+ val lineLeft: Float = left,
+ val lineTop: Float = top,
+ val lineRight: Float = right,
+ val lineBottom: Float = bottom
+ ) : ExportOverlay() {
+ fun toPdfTextEdit() = com.kyant.pdfcore.text.PdfTextEdit(
+ left, top, right, bottom, text, backgroundArgb, lineLeft, lineTop, lineRight, lineBottom
+ )
+ }
/** A real PDF sticky-note annotation anchored at [position] (top-left of icon). */
data class NoteStamp(
@@ -170,6 +182,8 @@ data class PdfViewerUiState(
val originalUri: Uri? = null,
val sizeBytes: Long = -1,
val ocrBlocksByPage: Map<Int, List<OcrTextBlock>> = emptyMap(),
+ /** The PDF's fillable form boxes, by page — filled in place in Edit mode (#68). */
+ val formWidgetsByPage: Map<Int, List<com.kyant.pdfcore.form.PdfFormWidget>> = emptyMap(),
val ocrPagesInProgress: Set<Int> = emptySet(),
val isExporting: Boolean = false,
val exportMessage: String? = null,
@@ -318,6 +332,7 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
sizeBytes = doc.sizeBytes,
pageBitmaps = List(doc.pageCount) { if (it == resumePage) firstPaint else null },
ocrBlocksByPage = emptyMap(),
+ formWidgetsByPage = emptyMap(),
ocrPagesInProgress = emptySet(),
isExporting = false,
exportMessage = null,
@@ -326,6 +341,16 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
showOfficeEngineHint = com.chethan616.clearpdf.office.OfficeEngine.shouldOfferHint(context, displayName),
renderedByOfficeEngine = renderedUri.path?.contains("/office-pdf/") == true
)
+ // Fillable fields, read off the main thread; most PDFs have none and stay empty.
+ val formDocUri = doc.uri
+ viewModelScope.launch {
+ val widgets = withContext(Dispatchers.IO) {
+ runCatching { com.kyant.pdfcore.form.PdfFormWidgets.read(context, formDocUri) }.getOrDefault(emptyMap())
+ }
+ if (widgets.isNotEmpty() && _uiState.value.document?.uri == formDocUri) {
+ _uiState.value = _uiState.value.copy(formWidgetsByPage = widgets)
+ }
+ }
// The ORIGINAL uri, deliberately — not `openedUri`.
//
// `openedUri` is whatever we ended up rendering: for a plain PDF that is the same
@@ -782,6 +807,11 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
?: throw IllegalStateException("Cannot open source PDF")
com.tom_roush.pdfbox.pdmodel.PDDocument.load(inputStream).use { pdDoc ->
+ // Form values first: the fields regenerate their own appearances in the form's fonts,
+ // and any markup is then drawn above them.
+ val formValues = overlaysByPage.values.flatten().filterIsInstance<ExportOverlay.FormValue>()
+ .associate { it.fieldName to it.value }
+ if (formValues.isNotEmpty()) runCatching { com.kyant.pdfcore.form.PdfFormWidgets.apply(pdDoc, formValues) }
overlaysByPage.forEach { (pageIdx, overlays) ->
if (pageIdx !in 0 until pdDoc.numberOfPages) return@forEach
val page = pdDoc.getPage(pageIdx)
@@ -790,9 +820,7 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
// Real text edits first: they rewrite the page's own content stream, and every
// other overlay is then drawn above the edited text.
- val textEdits = overlays.filterIsInstance<ExportOverlay.TextReplace>().map {
- com.kyant.pdfcore.text.PdfTextEdit(it.left, it.top, it.right, it.bottom, it.text, it.backgroundArgb)
- }
+ val textEdits = overlays.filterIsInstance<ExportOverlay.TextReplace>().map { it.toPdfTextEdit() }
if (textEdits.isNotEmpty()) {
runCatching { com.kyant.pdfcore.text.PdfTextEditor.applyEdits(pdDoc, pageIdx, textEdits) }
}
@@ -969,8 +997,9 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
cs.endText()
}
- // Already applied to the content stream before this pass.
+ // Already applied to the content stream / form before this pass.
is ExportOverlay.TextReplace -> Unit
+ is ExportOverlay.FormValue -> Unit
is ExportOverlay.NoteStamp -> {
// A real, clickable PDF sticky-note annotation.
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index c4f079b..f60a5a9 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -327,6 +327,11 @@
<string name="text_edit_title">Edit text</string>
<string name="text_edit_hint">Rewrites this line of the document in its own font. Tap empty space with the Text tool to add new text instead.</string>
<string name="text_edit_revert">Restore</string>
+ <string name="form_fill_previous">Previous field</string>
+ <string name="form_fill_next">Next field</string>
+ <string name="tour_form_title">Fill the form on the page</string>
+ <string name="tour_form_message">Tap a highlighted field to type, tick or choose. It saves in the form\'s own style.</string>
+ <string name="text_edit_hint_selection">Only the selected text changes, in the document\'s own font. The rest of the line moves to fit.</string>
<string name="text_edit_original">Original: %1$s</string>
<string name="not_now">Not now</string>
<string name="dont_ask_again">Don\'t ask again</string>
@@ -777,7 +782,9 @@
<string name="whats_new_title">What\'s new</string>
<string name="whats_new_subtitle">Here\'s what changed since your last version.</string>
<string name="whats_new_edit_title">Edit PDF text</string>
- <string name="whats_new_edit_desc">Rewrite any line in its own font. Tap it with the Text tool, or long-press a word.</string>
+ <string name="whats_new_edit_desc">Select words and tap Edit text, or tap a line with the Text tool. Only what you change is rewritten, in the document\'s own font.</string>
+ <string name="whats_new_forms_title">Fill forms on the page</string>
+ <string name="whats_new_forms_desc">In Edit mode, tap a form field to type, tick or choose right where it\'s printed.</string>
<string name="whats_new_glass_title">Liquid Glass settings</string>
<string name="whats_new_glass_desc">Tune blur, refraction and tint, or pick a preset.</string>
<string name="whats_new_share_title">Share in more formats</string>
diff --git a/app/src/test/java/com/chethan616/clearpdf/ui/screen/TextEditSegmentTest.kt b/app/src/test/java/com/chethan616/clearpdf/ui/screen/TextEditSegmentTest.kt
new file mode 100644
index 0000000..070fe5f
--- /dev/null
+++ b/app/src/test/java/com/chethan616/clearpdf/ui/screen/TextEditSegmentTest.kt
@@ -0,0 +1,84 @@
+package com.chethan616.clearpdf.ui.screen
+
+import androidx.compose.ui.geometry.Rect
+import androidx.compose.ui.graphics.Color
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNull
+import org.junit.Test
+
+/**
+ * In-place text editing rewrites only what changed: a selection edits just its words, and the
+ * save path gets a box around the changed words plus the line box (so the rest of the line can
+ * move by the change in width), never the whole line.
+ */
+class TextEditSegmentTest {
+
+ private val line = "Invoice number 1042 due on Friday"
+
+ /** One normalized unit per character, so a box's edges name its character range. */
+ private fun markup(text: String) = PdfMarkup.TextEditMarkup(
+ id = 1L, blockId = "b", rect = Rect(0f, 10f, line.length.toFloat(), 20f), baseline = 18f, fontSize = 10f,
+ original = line, text = text, color = Color.Black, background = Color.White,
+ bold = false, italic = false, serif = true, mono = false,
+ charLefts = FloatArray(line.length) { it.toFloat() / line.length },
+ charRights = FloatArray(line.length) { (it + 1f) / line.length }
+ )
+
+ private fun charIndex(x: Float) = Math.round(x * line.length)
+
+ @Test fun diffFindsTheChangedSpan() {
+ val (p, oEnd, cEnd) = textDiff(line, "Invoice number 2077-B due on Friday")
+ assertEquals(15, p)
+ assertEquals(19, oEnd)
+ assertEquals(21, cEnd)
+ }
+
+ @Test fun selectionMapsIntoAnEditedLine() {
+ val edited = "Invoice number 2077-B due on Friday"
+ // "Friday" sits after the earlier change, so it shifts by the change in length.
+ val fri = line.indexOf("Friday")
+ val r = selectionInCurrent(line, edited, fri, fri + 6)
+ assertEquals("Friday", edited.substring(r.first, r.last + 1))
+ // Touching the earlier change grows the selection to include all of it.
+ val num = line.indexOf("1042")
+ val g = selectionInCurrent(line, edited, num, num + 2)
+ assertEquals("2077-B", edited.substring(g.first, g.last + 1))
+ // Unedited line: the selection is unchanged.
+ val same = selectionInCurrent(line, line, 0, 7)
+ assertEquals("Invoice", line.substring(same.first, same.last + 1))
+ }
+
+ @Test fun onlyTheChangedWordIsRewritten() {
+ val r = markup("Invoice number 2077-B due on Friday").toTextReplace(line.length.toFloat(), 30f)!!
+ assertEquals("2077-B", r.text)
+ assertEquals(line.indexOf("1042"), charIndex(r.left))
+ assertEquals(line.indexOf("1042") + 4, charIndex(r.right))
+ // The line box stays the whole line, so the words after it can move.
+ assertEquals(0f, r.lineLeft, 1e-6f)
+ assertEquals(1f, r.lineRight, 1e-6f)
+ }
+
+ @Test fun partOfAWordGrowsToTheWord() {
+ val r = markup("Invoice number 1042 due on Monday").toTextReplace(line.length.toFloat(), 30f)!!
+ assertEquals("Monday", r.text)
+ assertEquals(line.indexOf("Friday"), charIndex(r.left))
+ }
+
+ @Test fun insertingBetweenWordsAnchorsOnANeighbour() {
+ val r = markup("Invoice number 1042 is due on Friday").toTextReplace(line.length.toFloat(), 30f)!!
+ // The inserted word rides on the word it was typed before, so there is a glyph to copy.
+ assertEquals("is due", r.text)
+ assertEquals(line.indexOf("due"), charIndex(r.left))
+ }
+
+ @Test fun unchangedTextHasNoEdit() {
+ assertNull(markup(line).toTextReplace(line.length.toFloat(), 30f))
+ }
+
+ @Test fun rewritingEverythingIsAWholeLineEdit() {
+ val r = markup("Completely different").toTextReplace(line.length.toFloat(), 30f)!!
+ assertEquals("Completely different", r.text)
+ assertEquals(r.lineLeft, r.left, 1e-6f)
+ assertEquals(r.lineRight, r.right, 1e-6f)
+ }
+}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/form/PdfFormWidgets.kt b/pdf-core/src/main/java/com/kyant/pdfcore/form/PdfFormWidgets.kt
new file mode 100644
index 0000000..09ec53a
--- /dev/null
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/form/PdfFormWidgets.kt
@@ -0,0 +1,212 @@
+package com.kyant.pdfcore.form
+
+import android.content.Context
+import android.net.Uri
+import com.kyant.pdfcore.internal.PdfBox
+import com.tom_roush.pdfbox.cos.COSBase
+import com.tom_roush.pdfbox.cos.COSName
+import com.tom_roush.pdfbox.pdmodel.PDDocument
+import com.tom_roush.pdfbox.pdmodel.common.PDRectangle
+import com.tom_roush.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget
+import com.tom_roush.pdfbox.pdmodel.interactive.form.PDCheckBox
+import com.tom_roush.pdfbox.pdmodel.interactive.form.PDChoice
+import com.tom_roush.pdfbox.pdmodel.interactive.form.PDField
+import com.tom_roush.pdfbox.pdmodel.interactive.form.PDNonTerminalField
+import com.tom_roush.pdfbox.pdmodel.interactive.form.PDRadioButton
+import com.tom_roush.pdfbox.pdmodel.interactive.form.PDTextField
+import com.tom_roush.pdfbox.pdmodel.interactive.form.PDVariableText
+
+/**
+ * One on-page box of an AcroForm field, so a viewer can let people fill the form where it is
+ * printed instead of in a list of field names. Geometry is normalized (0..1) in display space:
+ * top-left origin, page rotation applied, like the viewer's text blocks.
+ */
+data class PdfFormWidget(
+ val fieldName: String,
+ val type: Type,
+ val pageIndex: Int,
+ val left: Float,
+ val top: Float,
+ val right: Float,
+ val bottom: Float,
+ val value: String,
+ /** Choice fields: what the list shows. */
+ val options: List<String> = emptyList(),
+ /** Checkbox / radio: the value this box sets when on. */
+ val onValue: String = "",
+ /** From the field's default appearance: points (0 = auto-size) and as a fraction of page height. */
+ val fontSize: Float = 0f,
+ val fontSizeNorm: Float = 0f,
+ val textArgb: Int = 0xFF000000.toInt(),
+ /** 0 left, 1 centred, 2 right (the field's /Q). */
+ val alignment: Int = 0,
+ val multiline: Boolean = false,
+ val maxLength: Int = -1,
+ val comb: Boolean = false,
+ val password: Boolean = false,
+ val readOnly: Boolean = false,
+ /** The page's display height in points, to turn point sizes and paddings into pixels. */
+ val pageHeightPt: Float = 792f
+) {
+ enum class Type { TEXT, CHECKBOX, RADIO, CHOICE }
+
+ /** Unique per box: radio groups and repeated fields share a name. */
+ val key: String get() = "$fieldName#$pageIndex#${(left * 10000).toInt()}#${(top * 10000).toInt()}"
+}
+
+object PdfFormWidgets {
+
+ /** Every fillable box in the document, by page (empty when it has no form). */
+ fun read(context: Context, uri: Uri): Map<Int, List<PdfFormWidget>> {
+ PdfBox.ensureInitialized(context)
+ return runCatching {
+ context.contentResolver.openInputStream(uri)?.use { input ->
+ PDDocument.load(input).use { doc -> read(doc) }
+ } ?: emptyMap()
+ }.getOrDefault(emptyMap())
+ }
+
+ fun read(doc: PDDocument): Map<Int, List<PdfFormWidget>> {
+ val acro = doc.documentCatalog?.acroForm ?: return emptyMap()
+ // Widgets don't always name their page (/P), so map annotation objects to pages once.
+ val pageOf = HashMap<COSBase, Int>()
+ for (i in 0 until doc.numberOfPages) {
+ runCatching { doc.getPage(i).annotations }.getOrNull()?.forEach { pageOf[it.cosObject] = i }
+ }
+ val out = ArrayList<PdfFormWidget>()
+ fun visit(field: PDField) {
+ when (field) {
+ is PDNonTerminalField -> field.children?.forEach { visit(it) }
+ is PDTextField -> field.widgets.forEach { w ->
+ widget(doc, w, pageOf, field.fullyQualifiedName, PdfFormWidget.Type.TEXT, field.valueAsString.orEmpty(), field)?.let {
+ out += it.copy(
+ multiline = field.isMultiline,
+ maxLength = field.maxLen,
+ comb = field.isComb,
+ password = field.isPassword
+ )
+ }
+ }
+ is PDCheckBox -> field.widgets.forEach { w ->
+ val on = onValueOf(w) ?: runCatching { field.onValue }.getOrNull().orEmpty()
+ widget(doc, w, pageOf, field.fullyQualifiedName, PdfFormWidget.Type.CHECKBOX, if (field.isChecked) "true" else "false", field)
+ ?.let { out += it.copy(onValue = on) }
+ }
+ is PDRadioButton -> field.widgets.forEach { w ->
+ val on = onValueOf(w) ?: return@forEach
+ widget(doc, w, pageOf, field.fullyQualifiedName, PdfFormWidget.Type.RADIO, field.valueAsString.orEmpty(), field)
+ ?.let { out += it.copy(onValue = on) }
+ }
+ is PDChoice -> field.widgets.forEach { w ->
+ val options = runCatching { field.optionsDisplayValues }.getOrNull().orEmpty()
+ .ifEmpty { runCatching { field.optionsExportValues }.getOrNull().orEmpty() }
+ widget(doc, w, pageOf, field.fullyQualifiedName, PdfFormWidget.Type.CHOICE, field.valueAsString.orEmpty().trim('[', ']'), field)
+ ?.let { out += it.copy(options = options) }
+ }
+ else -> Unit // push buttons, signatures
+ }
+ }
+ runCatching { acro.fields }.getOrNull()?.forEach { runCatching { visit(it) } }
+ return out.groupBy { it.pageIndex }
+ }
+
+ /**
+ * Writes [values] (field name → value; "true"/"false" for checkboxes, the on-value for radio
+ * groups) into the document's form, regenerating each field's appearance in its own font
+ * settings. Returns how many fields were set.
+ */
+ fun apply(doc: PDDocument, values: Map<String, String>): Int {
+ if (values.isEmpty()) return 0
+ val acro = doc.documentCatalog?.acroForm ?: return 0
+ var count = 0
+ for ((name, value) in values) {
+ val field = runCatching { acro.getField(name) }.getOrNull() ?: continue
+ val ok = runCatching {
+ when (field) {
+ is PDCheckBox -> if (value == "true") field.check() else field.unCheck()
+ is PDRadioButton -> field.setValue(value)
+ is PDTextField -> field.setValue(value)
+ is PDChoice -> field.setValue(value)
+ else -> return@runCatching false
+ }
+ true
+ }.getOrDefault(false)
+ if (ok) count++
+ }
+ return count
+ }
+
+ private fun widget(
+ doc: PDDocument,
+ w: PDAnnotationWidget,
+ pageOf: Map<COSBase, Int>,
+ name: String,
+ type: PdfFormWidget.Type,
+ value: String,
+ field: PDField
+ ): PdfFormWidget? {
+ val text = field as? PDVariableText
+ if (w.isHidden || w.isNoView) return null
+ val pageIndex = pageOf[w.cosObject] ?: w.page?.let { p -> doc.pages.indexOf(p).takeIf { it >= 0 } } ?: return null
+ val page = doc.getPage(pageIndex)
+ val box = page.cropBox ?: page.mediaBox ?: return null
+ val r = w.rectangle ?: return null
+ val rotation = ((page.rotation % 360) + 360) % 360
+ val norm = normalize(r, box, rotation) ?: return null
+ val dispH = if (rotation == 90 || rotation == 270) box.width else box.height
+ val da = text?.let { runCatching { it.defaultAppearance }.getOrNull() }.orEmpty()
+ val size = Regex("""([0-9.]+)\s+Tf""").find(da)?.groupValues?.get(1)?.toFloatOrNull() ?: 0f
+ return PdfFormWidget(
+ fieldName = name,
+ type = type,
+ pageIndex = pageIndex,
+ left = norm[0], top = norm[1], right = norm[2], bottom = norm[3],
+ value = value,
+ fontSize = size,
+ fontSizeNorm = if (dispH > 0f) size / dispH else 0f,
+ pageHeightPt = dispH,
+ textArgb = colorOf(da),
+ alignment = text?.let { runCatching { it.q }.getOrDefault(0) } ?: 0,
+ readOnly = runCatching { field.isReadOnly }.getOrDefault(false)
+ )
+ }
+
+ /** The appearance state that means "on" for a checkbox / radio box (anything but /Off). */
+ private fun onValueOf(w: PDAnnotationWidget): String? = runCatching {
+ w.appearance?.normalAppearance?.takeIf { it.isSubDictionary }?.subDictionary?.keys
+ ?.firstOrNull { it != COSName.Off }?.name
+ }.getOrNull()
+
+ /** PDF user space → normalized display rect (left, top, right, bottom). */
+ private fun normalize(r: PDRectangle, box: PDRectangle, rotation: Int): FloatArray? {
+ val w = box.width
+ val h = box.height
+ if (w <= 0f || h <= 0f) return null
+ fun map(x: Float, y: Float): Pair<Float, Float> = when (rotation) {
+ 90 -> (y - box.lowerLeftY) / h to (x - box.lowerLeftX) / w
+ 180 -> (box.upperRightX - x) / w to (y - box.lowerLeftY) / h
+ 270 -> (box.upperRightY - y) / h to (box.upperRightX - x) / w
+ else -> (x - box.lowerLeftX) / w to (box.upperRightY - y) / h
+ }
+ val a = map(r.lowerLeftX, r.lowerLeftY)
+ val b = map(r.upperRightX, r.upperRightY)
+ val l = minOf(a.first, b.first).coerceIn(0f, 1f)
+ val t = minOf(a.second, b.second).coerceIn(0f, 1f)
+ val rr = maxOf(a.first, b.first).coerceIn(0f, 1f)
+ val bb = maxOf(a.second, b.second).coerceIn(0f, 1f)
+ return if (rr - l <= 0f || bb - t <= 0f) null else floatArrayOf(l, t, rr, bb)
+ }
+
+ /** The text colour in a default appearance string ("0 g", "1 0 0 rg"); black otherwise. */
+ private fun colorOf(da: String): Int {
+ fun c(v: String) = ((v.toFloatOrNull() ?: 0f).coerceIn(0f, 1f) * 255f + 0.5f).toInt()
+ Regex("""([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+rg""").find(da)?.groupValues?.let {
+ return (0xFF shl 24) or (c(it[1]) shl 16) or (c(it[2]) shl 8) or c(it[3])
+ }
+ Regex("""([0-9.]+)\s+g(?:\s|$)""").find(da)?.groupValues?.let {
+ val g = c(it[1])
+ return (0xFF shl 24) or (g shl 16) or (g shl 8) or g
+ }
+ return 0xFF000000.toInt()
+ }
+}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextEditPreview.kt b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextEditPreview.kt
new file mode 100644
index 0000000..7b9d5ac
--- /dev/null
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextEditPreview.kt
@@ -0,0 +1,87 @@
+package com.kyant.pdfcore.text
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Matrix
+import android.graphics.RectF
+import android.graphics.pdf.PdfRenderer
+import android.net.Uri
+import android.os.ParcelFileDescriptor
+import com.kyant.pdfcore.internal.PdfBox
+import com.tom_roush.pdfbox.pdmodel.PDDocument
+import java.io.File
+import kotlin.math.roundToInt
+
+/**
+ * What an in-place text edit will really look like: the page is edited with [PdfTextEditor] (the
+ * same code the save path runs) and rendered by the same engine as the viewer's pages, then cut
+ * into horizontal bands around the edited lines. The viewer lays those bands over its page bitmap,
+ * so the preview is the saved result, pixel for pixel, not an approximation in a system font.
+ */
+object PdfTextEditPreview {
+
+ /**
+ * Renders [bands] (normalized display-space rects) of page [pageIndex] after [edits], at a page
+ * width of [pageWidthPx]. Returns one bitmap per band, null where rendering failed (an
+ * encrypted file, an out-of-memory page); callers keep their quick preview for those.
+ */
+ fun render(
+ context: Context,
+ uri: Uri,
+ pageIndex: Int,
+ edits: List<PdfTextEdit>,
+ bands: List<RectF>,
+ pageWidthPx: Int
+ ): List<Bitmap?> {
+ if (bands.isEmpty() || pageWidthPx <= 0) return emptyList()
+ PdfBox.ensureInitialized(context)
+ val tmp = runCatching { File.createTempFile("text_edit_preview", ".pdf", context.cacheDir) }.getOrNull()
+ ?: return bands.map { null }
+ try {
+ val saved = runCatching {
+ context.contentResolver.openInputStream(uri)?.use { input ->
+ PDDocument.load(input).use { doc ->
+ if (pageIndex !in 0 until doc.numberOfPages) return@use false
+ PdfTextEditor.applyEdits(doc, pageIndex, edits)
+ // Only the edited page: a smaller file to write and for the renderer to open.
+ for (i in doc.numberOfPages - 1 downTo 0) if (i != pageIndex) doc.removePage(i)
+ doc.save(tmp)
+ true
+ }
+ } ?: false
+ }.getOrDefault(false)
+ if (!saved) return bands.map { null }
+
+ return ParcelFileDescriptor.open(tmp, ParcelFileDescriptor.MODE_READ_ONLY).use { fd ->
+ PdfRenderer(fd).use { renderer ->
+ val page = renderer.openPage(0)
+ try {
+ val srcW = page.width.toFloat().coerceAtLeast(1f)
+ val srcH = page.height.toFloat().coerceAtLeast(1f)
+ val pageHeightPx = pageWidthPx * (srcH / srcW)
+ bands.map { b ->
+ runCatching {
+ val w = ((b.right - b.left) * pageWidthPx).roundToInt().coerceAtLeast(1)
+ val h = ((b.bottom - b.top) * pageHeightPx).roundToInt().coerceAtLeast(1)
+ val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
+ bitmap.eraseColor(android.graphics.Color.WHITE)
+ val m = Matrix().apply {
+ postScale(pageWidthPx / srcW, pageHeightPx / srcH)
+ postTranslate(-b.left * pageWidthPx, -b.top * pageHeightPx)
+ }
+ page.render(bitmap, null, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
+ bitmap
+ }.getOrNull()
+ }
+ } finally {
+ runCatching { page.close() }
+ }
+ }
+ }
+ } catch (_: Throwable) {
+ return bands.map { null }
+ } finally {
+ tmp.delete()
+ }
+ }
+}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextEditor.kt b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextEditor.kt
index 7cbd52d..94d25a3 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextEditor.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextEditor.kt
@@ -1,9 +1,5 @@
package com.kyant.pdfcore.text
-import android.graphics.Bitmap
-import android.graphics.Canvas
-import android.graphics.Paint
-import android.graphics.Typeface
import com.tom_roush.pdfbox.contentstream.operator.Operator
import com.tom_roush.pdfbox.cos.COSArray
import com.tom_roush.pdfbox.cos.COSBase
@@ -23,19 +19,25 @@ import com.tom_roush.pdfbox.pdmodel.font.PDType1Font
import com.tom_roush.pdfbox.pdmodel.font.PDType3Font
import com.tom_roush.pdfbox.pdmodel.font.PDVectorFont
import com.tom_roush.pdfbox.pdmodel.graphics.form.PDFormXObject
-import com.tom_roush.pdfbox.pdmodel.graphics.image.LosslessFactory
import com.tom_roush.pdfbox.pdmodel.graphics.state.RenderingMode
import com.tom_roush.pdfbox.text.PDFTextStripper
import com.tom_roush.pdfbox.text.TextPosition
import com.tom_roush.pdfbox.util.Matrix
+import com.tom_roush.pdfbox.util.Vector
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.File
+import kotlin.math.abs
/**
- * Replace the text inside one line's box with [newText]. The box is normalized (0..1) in the same
- * display space [PdfTextService] reports blocks in: top-left origin, page rotation applied.
- * [backgroundArgb] paints behind the new text only when the original glyphs cannot be removed.
+ * Replace the text inside a box with [newText]. Boxes are normalized (0..1) in the same display
+ * space [PdfTextService] reports blocks in: top-left origin, page rotation applied.
+ *
+ * The edit box ([left]..[bottom]) holds the glyphs being replaced: a selection inside a line, or the
+ * whole line. The line box ([lineLeft]..[lineBottom]) is the full line. When the edit box is only
+ * part of it, the glyphs after the selection are moved by exactly the change in width, so a longer
+ * or shorter replacement neither overlaps nor leaves a gap. [backgroundArgb] paints behind the new
+ * text only when the original glyphs cannot be removed.
*/
data class PdfTextEdit(
val left: Float,
@@ -43,32 +45,43 @@ data class PdfTextEdit(
val right: Float,
val bottom: Float,
val newText: String,
- val backgroundArgb: Int = 0xFFFFFFFF.toInt()
+ val backgroundArgb: Int = 0xFFFFFFFF.toInt(),
+ val lineLeft: Float = left,
+ val lineTop: Float = top,
+ val lineRight: Float = right,
+ val lineBottom: Float = bottom
)
/**
- * In-place editing of a PDF's existing text — a real edit, not a sticker over the page.
+ * In-place editing of a PDF's existing text: a real edit, not a sticker over the page.
*
* For each edit:
* 1. The page's content stream is replayed with operator bookkeeping, so every glyph is tied to
- * the exact text-showing operator (`Tj`, `TJ`, `'`, `"`) that drew it.
- * 2. The glyphs inside the edited box are **removed from the content stream**. Each removed glyph
+ * the exact text-showing operator (`Tj`, `TJ`, `'`, `"`) and the exact bytes that drew it.
+ * 2. The glyphs inside the edit box are **removed from the content stream**. Each removed glyph
* becomes a `TJ` spacing adjustment of exactly its own advance, so every other glyph in the run
- * stays exactly where it was. The old text is gone (not hidden): it no longer renders, selects,
- * searches or extracts.
- * 3. The new text is drawn with **the original font** at the original text rendering matrix (size,
- * position, rotation, horizontal scale, colour), so it matches the line it replaces. If that font
- * cannot draw the new characters (embedded subsets usually hold only the glyphs the document
- * used), the closest standard face (serif / sans / mono, bold, italic) is used, then an
- * embedded system TrueType font, and as a last resort the text is rendered as an image, which
- * handles any script.
+ * stays put. The old text is gone (not hidden): it no longer renders, selects, searches or
+ * extracts.
+ * 3. The new text is drawn at the first removed glyph's text rendering matrix (size, position,
+ * rotation, horizontal scale, character and word spacing, colour), **character by character in
+ * the original font wherever possible**:
+ * - a character the document already draws in that font reuses those exact bytes, so even an
+ * embedded subset (which PDF libraries can't encode new text into) draws its own glyph;
+ * - otherwise the font's own encoding, if it has the glyph;
+ * - otherwise the closest face (same serif / sans / mono, weight and slant) for that character.
+ * Scripts no PDF font here can draw are laid out by Android and placed as an image.
+ * 4. On a partial edit, the rest of the line is re-drawn from its original bytes and fonts, shifted
+ * by the change in width, so it looks exactly as before.
*
- * Text it cannot surgically remove — inside form XObjects, Type 3 or vertical fonts, or the
- * invisible OCR layer of a scanned page — falls back to painting [PdfTextEdit.backgroundArgb]
- * over the old line before drawing the new text.
+ * Text it cannot surgically remove (inside form XObjects, Type 3 or vertical fonts, or the
+ * invisible OCR layer of a scanned page) falls back to painting [PdfTextEdit.backgroundArgb]
+ * over the old text before drawing the new text.
*/
object PdfTextEditor {
+ /** How many other pages may be scanned for a character the edited page never drew. */
+ private const val HarvestPageLimit = 80
+
fun applyEdits(doc: PDDocument, pageIndex: Int, edits: List<PdfTextEdit>) {
if (edits.isEmpty() || pageIndex !in 0 until doc.numberOfPages) return
val page = doc.getPage(pageIndex)
@@ -76,8 +89,10 @@ object PdfTextEditor {
val rotation = ((page.rotation % 360) + 360) % 360
val (dispW, dispH) = if (rotation == 90 || rotation == 270) box.height to box.width else box.width to box.height
if (dispW <= 0f || dispH <= 0f) return
+ val llx = box.lowerLeftX
+ val lly = box.lowerLeftY
- val recorder = GlyphRecorder().apply {
+ val recorder = GlyphRecorder(collectGlyphs = true).apply {
startPage = pageIndex + 1
endPage = pageIndex + 1
}
@@ -86,26 +101,37 @@ object PdfTextEditor {
val tokens = runCatching { parseTokens(page) }.getOrNull()
val operatorIndex = tokens?.indices?.filter { tokens[it] is Operator }.orEmpty()
- // Per edit: which recorded glyphs it covers, and whether they can be removed surgically.
- class Plan(val edit: PdfTextEdit, val glyphs: List<Glyph>, val removable: Boolean)
+ fun inBox(g: Glyph, l: Float, t: Float, r: Float, b: Float): Boolean {
+ val cx = (g.tp.x + g.tp.width / 2f) / dispW
+ val by = g.tp.y / dispH
+ val slack = (b - t) * 0.25f
+ return cx >= l && cx <= r && by >= t - slack && by <= b + slack
+ }
+ fun removable(g: Glyph): Boolean = tokens != null && g.depth == 0 &&
+ g.renderMode != RenderingMode.NEITHER && g.font !is PDType3Font && !g.font.isVertical &&
+ g.tfs != 0f && g.bytes.isNotEmpty() &&
+ operatorIndex.getOrNull(g.op)?.let { (tokens[it] as Operator).name in TextShowOps } == true
+
+ // Per edit: the glyphs it replaces, the rest of its line that has to move, and whether
+ // both can be removed surgically.
+ class Plan(val edit: PdfTextEdit, val hit: List<Glyph>, val suffix: List<Glyph>, val removable: Boolean, val partial: Boolean)
val plans = edits.map { e ->
- val hit = recorder.glyphs.filter { g ->
- val tp = g.tp
- val cx = (tp.x + tp.width / 2f) / dispW
- val by = tp.y / dispH
- val slack = (e.bottom - e.top) * 0.25f
- cx >= e.left && cx <= e.right && by >= e.top - slack && by <= e.bottom + slack
- }
- val removable = tokens != null && hit.isNotEmpty() && hit.all { g ->
- g.depth == 0 && g.renderMode != RenderingMode.NEITHER && g.font !is PDType3Font &&
- !g.font.isVertical && g.tfs != 0f &&
- operatorIndex.getOrNull(g.op)?.let { (tokens[it] as Operator).name in TextShowOps } == true
- }
- Plan(e, hit, removable)
+ val hit = recorder.glyphs.filter { inBox(it, e.left, e.top, e.right, e.bottom) }.sortedBy { it.tp.x }
+ val partial = e.lineLeft < e.left - 1e-4f || e.lineRight > e.right + 1e-4f
+ val last = hit.lastOrNull()
+ val hitSet = hit.toHashSet()
+ val lineH = (e.lineBottom - e.lineTop) * dispH
+ val suffix = if (!partial || last == null) emptyList() else recorder.glyphs.filter { g ->
+ g !in hitSet && g.tp.x > last.tp.x &&
+ inBox(g, e.lineLeft, e.lineTop, e.lineRight, e.lineBottom) &&
+ abs(g.tp.y - last.tp.y) <= lineH * 0.5f
+ }.sortedBy { it.tp.x }
+ val hitOk = hit.isNotEmpty() && hit.all(::removable)
+ Plan(e, hit, if (hitOk && suffix.all(::removable)) suffix else emptyList(), hitOk, partial)
}
// 1) Remove the old glyphs from the content stream (all edits on the page in one rewrite).
- val toRemove = plans.filter { it.removable }.flatMap { it.glyphs }
+ val toRemove = plans.filter { it.removable }.flatMap { it.hit + it.suffix }
var removedOk = false
if (toRemove.isNotEmpty() && tokens != null) {
removedOk = runCatching {
@@ -117,19 +143,28 @@ object PdfTextEditor {
}.getOrDefault(false)
}
- // 2) Draw the replacements on top, in a fresh, state-isolated stream.
+ // 2) Draw the replacements (and the moved rest of each line) in a fresh, state-isolated stream.
+ val fonts = FontSource(doc, recorder.codes, pageIndex)
PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true).use { cs ->
for (plan in plans) {
val e = plan.edit
val removed = plan.removable && removedOk
- if (!removed) coverOldLine(cs, e, box.lowerLeftX, box.lowerLeftY, dispW, dispH, rotation)
- val text = e.newText.replace('\n', ' ').trimEnd()
- if (text.isEmpty()) continue
- val first = plan.glyphs.minByOrNull { it.tp.x } ?: run {
- drawUnanchored(doc, cs, e, text, box.lowerLeftX, box.lowerLeftY, dispW, dispH, rotation)
+ if (!removed) coverOldText(cs, e, llx, lly, dispW, dispH, rotation)
+ val text = e.newText.replace('\n', ' ').let { if (plan.partial) it else it.trimEnd() }
+ val first = plan.hit.firstOrNull() ?: run {
+ if (text.isNotBlank()) drawUnanchored(doc, cs, e, text, fonts, llx, lly, dispW, dispH, rotation)
continue
}
- drawLike(doc, cs, first, text, box.lowerLeftX, box.lowerLeftY)
+ val advance = drawLike(doc, cs, first, text, fonts, llx, lly)
+ if (removed && plan.suffix.isNotEmpty()) {
+ val t0 = trmOf(first, llx, lly)
+ val lastHit = plan.hit.last()
+ val tl = trmOf(lastHit, llx, lly)
+ val aL = advanceOf(lastHit)
+ val dx = (t0.translateX + advance * t0.getValue(0, 0)) - (tl.translateX + aL * tl.getValue(0, 0))
+ val dy = (t0.translateY + advance * t0.getValue(0, 1)) - (tl.translateY + aL * tl.getValue(0, 1))
+ redrawShifted(cs, plan.suffix, dx, dy, llx, lly)
+ }
}
}
}
@@ -139,21 +174,31 @@ object PdfTextEditor {
private class Glyph(
val op: Int, // ordinal of the text-showing operator in the page's operator list
val str: Int, // which string operand of that operator (TJ arrays hold several)
- val idx: Int, // glyph index inside that string
+ val idx: Int, // code index inside that string (counts every code, drawn or not)
val depth: Int, // form XObject nesting (0 = page content)
val tp: TextPosition,
val font: PDFont,
+ val code: Int,
+ val bytes: ByteArray, // the exact bytes that drew this glyph
val tfs: Float, val tc: Float, val tw: Float, val th: Float,
val rgb: Int,
val renderMode: RenderingMode
)
- private class GlyphRecorder : PDFTextStripper() {
+ /**
+ * Replays a page (or pages) through the text extractor, recording each glyph and, per font,
+ * the bytes that drew each character, so new text can reuse them.
+ */
+ private class GlyphRecorder(private val collectGlyphs: Boolean) : PDFTextStripper() {
val glyphs = ArrayList<Glyph>()
+ val codes = CodeBook()
private var depth = 0
private var op = -1
private var str = -1
- private var idx = 0
+ private var codeIdx = -1
+ private var slices: List<ByteArray> = emptyList()
+ private var curBytes = ByteArray(0)
+ private var curCode = 0
override fun processOperator(operator: Operator, operands: MutableList<COSBase>) {
if (depth == 0) { op++; str = -1 }
@@ -166,16 +211,28 @@ object PdfTextEditor {
}
override fun showText(string: ByteArray) {
- if (depth == 0) { str++; idx = 0 }
+ if (depth == 0) str++
+ codeIdx = -1
+ slices = graphicsState.textState.font?.let { splitCodes(it, string) }.orEmpty()
super.showText(string)
}
+ override fun showGlyph(textRenderingMatrix: Matrix, font: PDFont, code: Int, unicode: String?, displacement: Vector) {
+ codeIdx++
+ curCode = code
+ curBytes = slices.getOrNull(codeIdx) ?: ByteArray(0)
+ if (!unicode.isNullOrEmpty() && curBytes.isNotEmpty()) codes.put(font, unicode, curBytes)
+ super.showGlyph(textRenderingMatrix, font, code, unicode, displacement)
+ }
+
override fun processTextPosition(text: TextPosition) {
+ if (!collectGlyphs) return
val gs = graphicsState
val ts = gs.textState
val font = text.font ?: ts.font ?: return
glyphs += Glyph(
- op = op, str = str, idx = idx++, depth = depth, tp = text, font = font,
+ op = op, str = str, idx = codeIdx, depth = depth, tp = text, font = font,
+ code = curCode, bytes = curBytes,
tfs = ts.fontSize, tc = ts.characterSpacing, tw = ts.wordSpacing,
th = ts.horizontalScaling / 100f,
rgb = runCatching { gs.nonStrokingColor.toRGB() }.getOrDefault(0),
@@ -184,6 +241,43 @@ object PdfTextEditor {
}
}
+ /** Character → drawing bytes, per font program. */
+ private class CodeBook {
+ private val byFont = HashMap<COSBase, HashMap<String, ByteArray>>()
+ // An embedded subset is identified by its tag ("ABCDEF+Arial"), so the same subset loaded
+ // as separate objects on different pages still shares its codes.
+ private val bySubsetName = HashMap<String, HashMap<String, ByteArray>>()
+
+ fun put(font: PDFont, unicode: String, bytes: ByteArray) {
+ byFont.getOrPut(font.cosObject) { HashMap() }.putIfAbsent(unicode, bytes)
+ subsetName(font)?.let { bySubsetName.getOrPut(it) { HashMap() }.putIfAbsent(unicode, bytes) }
+ }
+
+ fun get(font: PDFont, unicode: String): ByteArray? =
+ byFont[font.cosObject]?.get(unicode) ?: subsetName(font)?.let { bySubsetName[it]?.get(unicode) }
+
+ fun addAll(other: CodeBook) {
+ other.byFont.forEach { (k, v) -> val m = byFont.getOrPut(k) { HashMap() }; v.forEach { (u, b) -> m.putIfAbsent(u, b) } }
+ other.bySubsetName.forEach { (k, v) -> val m = bySubsetName.getOrPut(k) { HashMap() }; v.forEach { (u, b) -> m.putIfAbsent(u, b) } }
+ }
+
+ private fun subsetName(font: PDFont): String? =
+ font.name?.takeIf { it.length > 7 && it[6] == '+' }
+ }
+
+ private fun splitCodes(font: PDFont, string: ByteArray): List<ByteArray> = runCatching {
+ val input = ByteArrayInputStream(string)
+ val out = ArrayList<ByteArray>()
+ while (input.available() > 0) {
+ val start = string.size - input.available()
+ font.readCode(input)
+ val end = string.size - input.available()
+ if (end <= start) break
+ out += string.copyOfRange(start, end)
+ }
+ out
+ }.getOrDefault(emptyList())
+
private val TextShowOps = setOf("Tj", "TJ", "'", "\"")
private fun parseTokens(page: PDPage): MutableList<Any> {
@@ -283,47 +377,160 @@ object PdfTextEditor {
return out
}
- // ── Drawing the replacement ───────────────────────────────────────────────────────────
+ // ── Drawing ──────────────────────────────────────────────────────────────────────────
- /** Draws [text] exactly where and how [first] (the old line's first glyph) was drawn. */
- private fun drawLike(doc: PDDocument, cs: PDPageContentStream, first: Glyph, text: String, llx: Float, lly: Float) {
- // TextPosition's matrix is the text rendering matrix shifted by the crop box origin; undo it.
- val m = first.tp.textMatrix
- val trm = Matrix(
- m.getValue(0, 0), m.getValue(0, 1), m.getValue(1, 0), m.getValue(1, 1),
- m.translateX + llx, m.translateY + lly
- )
+ /** TextPosition's matrix is the text rendering matrix shifted by the crop box origin; undo it. */
+ private fun trmOf(g: Glyph, llx: Float, lly: Float): Matrix {
+ val m = g.tp.textMatrix
+ return Matrix(m.getValue(0, 0), m.getValue(0, 1), m.getValue(1, 0), m.getValue(1, 1), m.translateX + llx, m.translateY + lly)
+ }
+
+ /** A glyph's advance in units of its own text rendering matrix (font size and scale included). */
+ private fun advanceOf(g: Glyph): Float {
+ val w0 = runCatching { g.font.getWidth(g.code) }.getOrDefault(0f) / 1000f
+ val space = if (g.bytes.size == 1 && g.code == 32) g.tw else 0f
+ return w0 + (g.tc + space) / g.tfs
+ }
+
+ private sealed class Piece(val font: PDFont, val advance: Float) {
+ class Raw(font: PDFont, val bytes: ByteArray, advance: Float) : Piece(font, advance)
+ class Text(font: PDFont, val text: String, advance: Float) : Piece(font, advance)
+ class Gap(font: PDFont, val units: Float) : Piece(font, units / 1000f)
+ }
+
+ /**
+ * Draws [text] where and how [first] was drawn; returns its advance in [first]'s text rendering
+ * matrix units, so the rest of the line can follow it.
+ */
+ private fun drawLike(doc: PDDocument, cs: PDPageContentStream, first: Glyph, text: String, fonts: FontSource, llx: Float, lly: Float): Float {
+ if (text.isEmpty()) return 0f
+ val trm = trmOf(first, llx, lly)
+ val tcU = first.tc / first.tfs
+ val twU = first.tw / first.tfs
+ val pieces = encode(first.font, text, fonts, tcU, twU)
+ if (pieces == null) {
+ val t = traitsOf(first.font)
+ return PdfTextImageFallback.draw(doc, cs, text, trm, first.rgb, t.bold, t.italic, t.serif, t.mono)
+ }
val rgb = first.rgb
- val font = if (canShow(first.font, text)) first.font else fallbackFont(doc, first.font, text)
- if (font != null) {
- cs.beginText()
- cs.setNonStrokingColor((rgb shr 16) and 0xFF, (rgb shr 8) and 0xFF, rgb and 0xFF)
- // Size 1 at the full rendering matrix reproduces size, scale, skew and rotation exactly.
- cs.setFont(font, 1f)
- cs.setTextMatrix(trm)
- cs.showText(text)
- cs.endText()
- } else {
- drawAsImage(doc, cs, first.font, text, trm, rgb)
+ cs.beginText()
+ cs.setNonStrokingColor((rgb shr 16) and 0xFF, (rgb shr 8) and 0xFF, rgb and 0xFF)
+ // Size 1 at the full rendering matrix reproduces size, scale, skew and rotation exactly;
+ // spacing is scaled into the same units.
+ cs.setFont(pieces.first().font, 1f)
+ cs.setCharacterSpacing(tcU)
+ cs.setWordSpacing(twU)
+ cs.setTextMatrix(trm)
+ var font = pieces.first().font
+ var advance = 0f
+ for (p in pieces) {
+ if (p.font !== font && p !is Piece.Gap) { cs.setFont(p.font, 1f); font = p.font }
+ when (p) {
+ is Piece.Raw -> cs.appendRawCommands(hexShow(p.bytes))
+ is Piece.Text -> cs.showText(p.text)
+ is Piece.Gap -> cs.appendRawCommands("[" + num(-p.units) + "] TJ\n")
+ }
+ advance += p.advance
+ }
+ cs.endText()
+ return advance
+ }
+
+ /**
+ * Splits [text] into runs: the original font's own bytes first, then its encoding, then the
+ * closest face, per character. Null when some character can't be drawn by any PDF font here.
+ */
+ private fun encode(font: PDFont, text: String, fonts: FontSource, tcU: Float, twU: Float): List<Piece>? {
+ val out = ArrayList<Piece>()
+ fun add(p: Piece) {
+ val last = out.lastOrNull()
+ out += when {
+ last is Piece.Raw && p is Piece.Raw && last.font === p.font -> { out.removeAt(out.lastIndex); Piece.Raw(p.font, last.bytes + p.bytes, last.advance + p.advance) }
+ last is Piece.Text && p is Piece.Text && last.font === p.font -> { out.removeAt(out.lastIndex); Piece.Text(p.font, last.text + p.text, last.advance + p.advance) }
+ else -> p
+ }
+ }
+ var i = 0
+ while (i < text.length) {
+ val cp = text.codePointAt(i)
+ val ch = String(Character.toChars(cp))
+ i += Character.charCount(cp)
+ val raw = fonts.bytesFor(font, ch)
+ if (raw != null) {
+ val code = codeOf(font, raw)
+ val w = runCatching { font.getWidth(code) }.getOrDefault(0f) / 1000f
+ add(Piece.Raw(font, raw, w + tcU + if (raw.size == 1 && code == 32) twU else 0f))
+ continue
+ }
+ if (canShow(font, ch)) { add(Piece.Text(font, ch, textAdvance(font, ch, tcU, twU))); continue }
+ if (cp == ' '.code) {
+ val sw = runCatching { font.spaceWidth }.getOrDefault(0f).takeIf { it > 0f } ?: 250f
+ add(Piece.Gap(font, sw + tcU * 1000f))
+ continue
+ }
+ val fb = fonts.fallback(font, ch) ?: return null
+ add(Piece.Text(fb, ch, textAdvance(fb, ch, tcU, twU)))
+ }
+ return out
+ }
+
+ private fun textAdvance(font: PDFont, ch: String, tcU: Float, twU: Float): Float = runCatching {
+ val bytes = font.encode(ch)
+ val code = codeOf(font, bytes)
+ font.getWidth(code) / 1000f + tcU + if (bytes.size == 1 && code == 32) twU else 0f
+ }.getOrDefault(0f)
+
+ private fun codeOf(font: PDFont, bytes: ByteArray): Int =
+ runCatching { font.readCode(ByteArrayInputStream(bytes)) }.getOrElse {
+ var c = 0
+ for (b in bytes) c = (c shl 8) or (b.toInt() and 0xFF)
+ c
+ }
+
+ /** The rest of an edited line, re-drawn from its original bytes and fonts, moved by (dx, dy). */
+ private fun redrawShifted(cs: PDPageContentStream, glyphs: List<Glyph>, dx: Float, dy: Float, llx: Float, lly: Float) {
+ cs.beginText()
+ var font: PDFont? = null
+ var rgb = Int.MIN_VALUE
+ for (g in glyphs) {
+ if (g.rgb != rgb) { cs.setNonStrokingColor((g.rgb shr 16) and 0xFF, (g.rgb shr 8) and 0xFF, g.rgb and 0xFF); rgb = g.rgb }
+ if (g.font !== font) { cs.setFont(g.font, 1f); font = g.font }
+ val t = trmOf(g, llx, lly)
+ cs.setTextMatrix(Matrix(t.getValue(0, 0), t.getValue(0, 1), t.getValue(1, 0), t.getValue(1, 1), t.translateX + dx, t.translateY + dy))
+ cs.appendRawCommands(hexShow(g.bytes))
}
+ cs.endText()
}
+ private fun hexShow(bytes: ByteArray): String {
+ val sb = StringBuilder(bytes.size * 2 + 6).append('<')
+ for (b in bytes) {
+ val v = b.toInt() and 0xFF
+ sb.append(HEX[v shr 4]).append(HEX[v and 0xF])
+ }
+ return sb.append("> Tj\n").toString()
+ }
+
+ private const val HEX = "0123456789ABCDEF"
+
+ private fun num(v: Float): String = String.format(java.util.Locale.ROOT, "%.3f", v)
+
/** No glyph to copy (e.g. an empty OCR box): draw in a matching face sized to the box. */
private fun drawUnanchored(
- doc: PDDocument, cs: PDPageContentStream, e: PdfTextEdit, text: String,
+ doc: PDDocument, cs: PDPageContentStream, e: PdfTextEdit, text: String, fonts: FontSource,
llx: Float, lly: Float, dispW: Float, dispH: Float, rotation: Int
) {
if (rotation != 0) return
val size = (e.bottom - e.top) * dispH * 0.78f
if (size <= 0f) return
val trm = Matrix(size, 0f, 0f, size, llx + e.left * dispW, lly + (1f - e.bottom) * dispH + size * 0.22f)
- val font = fallbackFont(doc, null, text)
+ val font = fonts.fallbackFor(null, text)
if (font != null) {
cs.beginText(); cs.setNonStrokingColor(0, 0, 0); cs.setFont(font, 1f); cs.setTextMatrix(trm); cs.showText(text); cs.endText()
- } else drawAsImage(doc, cs, null, text, trm, 0)
+ } else PdfTextImageFallback.draw(doc, cs, text, trm, 0, false, false, false, false)
}
- private fun coverOldLine(
+ private fun coverOldText(
cs: PDPageContentStream, e: PdfTextEdit, llx: Float, lly: Float, dispW: Float, dispH: Float, rotation: Int
) {
if (rotation != 0) return
@@ -341,33 +548,61 @@ object PdfTextEditor {
cs.restoreGraphicsState()
}
- /**
- * Last resort, for scripts no available PDF font can draw (or that need shaping, which PDF
- * text output doesn't do — Devanagari, Arabic…): Android lays the text out with full shaping
- * and font fallback, and the result is placed on the baseline as an image.
- */
- private fun drawAsImage(doc: PDDocument, cs: PDPageContentStream, like: PDFont?, text: String, trm: Matrix, rgb: Int) {
- val pt = kotlin.math.hypot(trm.getValue(1, 0), trm.getValue(1, 1))
- if (pt <= 0f) return
- val scale = 4f // px per pt: sharp at print zoom
- val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
- textSize = pt * scale
- color = 0xFF000000.toInt() or rgb
- typeface = typefaceLike(like)
+ // ── Fonts ─────────────────────────────────────────────────────────────────────────────
+
+ /** Codes the document already uses, and fallback faces, for one document's edits. */
+ private class FontSource(private val doc: PDDocument, private val codes: CodeBook, private val pageIndex: Int) {
+ private var harvested = false
+ private val loaded = HashMap<String, PDFont?>()
+
+ fun bytesFor(font: PDFont, ch: String): ByteArray? {
+ codes.get(font, ch)?.let { return it }
+ // Many PDFs never draw a space (they position words instead): not worth a scan.
+ if (!harvested && ch.isNotBlank()) {
+ harvested = true
+ // Not drawn on this page: look through the rest of the document once.
+ val n = doc.numberOfPages
+ if (n > 1) {
+ val r = GlyphRecorder(collectGlyphs = false).apply {
+ startPage = 1
+ endPage = minOf(n, HarvestPageLimit)
+ }
+ runCatching { r.getText(doc) }
+ codes.addAll(r.codes)
+ }
+ }
+ return codes.get(font, ch)
}
- val fm = paint.fontMetrics
- val w = paint.measureText(text).coerceAtLeast(1f)
- val h = (fm.descent - fm.ascent).coerceAtLeast(1f)
- val bmp = Bitmap.createBitmap(w.toInt() + 2, h.toInt() + 2, Bitmap.Config.ARGB_8888)
- Canvas(bmp).drawText(text, 1f, -fm.ascent + 1f, paint)
- val image = runCatching { LosslessFactory.createFromImage(doc, bmp) }.getOrNull() ?: return
- bmp.recycle()
- val x = trm.translateX
- val y = trm.translateY - (fm.descent / scale)
- cs.drawImage(image, x, y, (w + 2f) / scale, (h + 2f) / scale)
- }
- // ── Fonts ─────────────────────────────────────────────────────────────────────────────
+ /** The closest face to [like] that can draw [ch]. */
+ fun fallback(like: PDFont, ch: String): PDFont? = fallbackFor(like, ch)
+
+ fun fallbackFor(like: PDFont?, text: String): PDFont? {
+ val t = traitsOf(like)
+ val std = when {
+ t.mono -> when { t.bold && t.italic -> PDType1Font.COURIER_BOLD_OBLIQUE; t.bold -> PDType1Font.COURIER_BOLD; t.italic -> PDType1Font.COURIER_OBLIQUE; else -> PDType1Font.COURIER }
+ t.serif -> when { t.bold && t.italic -> PDType1Font.TIMES_BOLD_ITALIC; t.bold -> PDType1Font.TIMES_BOLD; t.italic -> PDType1Font.TIMES_ITALIC; else -> PDType1Font.TIMES_ROMAN }
+ else -> when { t.bold && t.italic -> PDType1Font.HELVETICA_BOLD_OBLIQUE; t.bold -> PDType1Font.HELVETICA_BOLD; t.italic -> PDType1Font.HELVETICA_OBLIQUE; else -> PDType1Font.HELVETICA }
+ }
+ if (canShow(std, text)) return std
+ // Beyond Latin-1: embed (subset) a system TrueType face of the same style.
+ val weight = when { t.bold && t.italic -> "BoldItalic"; t.bold -> "Bold"; t.italic -> "Italic"; else -> "Regular" }
+ val names = buildList {
+ if (t.serif) { add("NotoSerif-$weight.ttf"); add("NotoSerif-Regular.ttf") }
+ if (t.mono) { add("DroidSansMono.ttf"); add("CutiveMono.ttf") }
+ add("Roboto-$weight.ttf"); add("RobotoStatic-$weight.ttf"); add("Roboto-Regular.ttf")
+ add("NotoSans-$weight.ttf"); add("NotoSans-Regular.ttf"); add("DroidSans.ttf")
+ }
+ for (n in names.distinct()) {
+ val font = loaded.getOrPut(n) {
+ val f = File("/system/fonts/$n")
+ if (f.exists()) runCatching { PDType0Font.load(doc, f) }.getOrNull() else null
+ } ?: continue
+ if (canShow(font, text)) return font
+ }
+ return null
+ }
+ }
/** Whether [font] can draw every character of [text] (embedded subsets often can't). */
private fun canShow(font: PDFont, text: String): Boolean = try {
@@ -399,43 +634,11 @@ object PdfTextEditor {
val d = font?.fontDescriptor
val bold = listOf("bold", "black", "heavy", "semibold", "demi").any { name.contains(it) } ||
d?.isForceBold == true || (d?.fontWeight ?: 400f) >= 600f
- val italic = name.contains("italic") || name.contains("oblique") || d?.isItalic == true
+ val italic = name.contains("italic") || name.contains("oblique") || d?.isItalic == true || (d?.italicAngle ?: 0f) != 0f
val mono = listOf("courier", "mono", "consol", "menlo").any { name.contains(it) } || d?.isFixedPitch == true
val serif = !mono && (d?.isSerif == true ||
listOf("times", "serif", "georgia", "garamond", "cambria", "book", "minion", "palatino", "baskerville").any { name.contains(it) } &&
!name.contains("sans"))
return Traits(bold, italic, serif, mono)
}
-
- private fun fallbackFont(doc: PDDocument, like: PDFont?, text: String): PDFont? {
- val t = traitsOf(like)
- val std = when {
- t.mono -> when { t.bold && t.italic -> PDType1Font.COURIER_BOLD_OBLIQUE; t.bold -> PDType1Font.COURIER_BOLD; t.italic -> PDType1Font.COURIER_OBLIQUE; else -> PDType1Font.COURIER }
- t.serif -> when { t.bold && t.italic -> PDType1Font.TIMES_BOLD_ITALIC; t.bold -> PDType1Font.TIMES_BOLD; t.italic -> PDType1Font.TIMES_ITALIC; else -> PDType1Font.TIMES_ROMAN }
- else -> when { t.bold && t.italic -> PDType1Font.HELVETICA_BOLD_OBLIQUE; t.bold -> PDType1Font.HELVETICA_BOLD; t.italic -> PDType1Font.HELVETICA_OBLIQUE; else -> PDType1Font.HELVETICA }
- }
- if (canShow(std, text)) return std
- // Beyond Latin-1: embed (subset) a system TrueType face of the same style.
- val weight = if (t.bold) "Bold" else "Regular"
- val names = buildList {
- if (t.serif) { add("NotoSerif-$weight.ttf"); add("NotoSerif-Regular.ttf") }
- if (t.mono) { add("DroidSansMono.ttf"); add("CutiveMono.ttf") }
- add("Roboto-$weight.ttf"); add("RobotoStatic-$weight.ttf"); add("Roboto-Regular.ttf")
- add("NotoSans-$weight.ttf"); add("NotoSans-Regular.ttf"); add("DroidSans.ttf")
- }
- for (n in names.distinct()) {
- val f = File("/system/fonts/$n")
- if (!f.exists()) continue
- val font = runCatching { PDType0Font.load(doc, f) }.getOrNull() ?: continue
- if (canShow(font, text)) return font
- }
- return null
- }
-
- private fun typefaceLike(font: PDFont?): Typeface {
- val t = traitsOf(font)
- val family = when { t.mono -> Typeface.MONOSPACE; t.serif -> Typeface.SERIF; else -> Typeface.SANS_SERIF }
- val style = when { t.bold && t.italic -> Typeface.BOLD_ITALIC; t.bold -> Typeface.BOLD; t.italic -> Typeface.ITALIC; else -> Typeface.NORMAL }
- return Typeface.create(family, style)
- }
}
diff --git a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextImageFallback.kt b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextImageFallback.kt
new file mode 100644
index 0000000..e39eca4
--- /dev/null
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextImageFallback.kt
@@ -0,0 +1,48 @@
+package com.kyant.pdfcore.text
+
+import android.graphics.Bitmap
+import android.graphics.Canvas
+import android.graphics.Paint
+import android.graphics.Typeface
+import com.tom_roush.pdfbox.pdmodel.PDDocument
+import com.tom_roush.pdfbox.pdmodel.PDPageContentStream
+import com.tom_roush.pdfbox.pdmodel.graphics.image.LosslessFactory
+import com.tom_roush.pdfbox.util.Matrix
+
+/**
+ * The text editor's last resort, kept apart from the PDF logic because it is the only Android-only
+ * part: scripts no available PDF font can draw (or that need shaping, which PDF text output doesn't
+ * do: Devanagari, Arabic…) are laid out by Android with full shaping and font fallback, and placed
+ * on the baseline as an image.
+ */
+internal object PdfTextImageFallback {
+
+ /** Draws [text] on [trm]'s baseline; returns its advance in [trm]'s units (0 if nothing drawn). */
+ fun draw(
+ doc: PDDocument, cs: PDPageContentStream, text: String, trm: Matrix, rgb: Int,
+ bold: Boolean, italic: Boolean, serif: Boolean, mono: Boolean
+ ): Float {
+ val pt = kotlin.math.hypot(trm.getValue(1, 0), trm.getValue(1, 1))
+ if (pt <= 0f) return 0f
+ val scale = 4f // px per pt: sharp at print zoom
+ val family = when { mono -> Typeface.MONOSPACE; serif -> Typeface.SERIF; else -> Typeface.SANS_SERIF }
+ val style = when { bold && italic -> Typeface.BOLD_ITALIC; bold -> Typeface.BOLD; italic -> Typeface.ITALIC; else -> Typeface.NORMAL }
+ val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = pt * scale
+ color = 0xFF000000.toInt() or rgb
+ typeface = Typeface.create(family, style)
+ }
+ val fm = paint.fontMetrics
+ val w = paint.measureText(text).coerceAtLeast(1f)
+ val h = (fm.descent - fm.ascent).coerceAtLeast(1f)
+ val bmp = Bitmap.createBitmap(w.toInt() + 2, h.toInt() + 2, Bitmap.Config.ARGB_8888)
+ Canvas(bmp).drawText(text, 1f, -fm.ascent + 1f, paint)
+ val image = runCatching { LosslessFactory.createFromImage(doc, bmp) }.getOrNull() ?: return 0f
+ bmp.recycle()
+ val x = trm.translateX
+ val y = trm.translateY - (fm.descent / scale)
+ cs.drawImage(image, x, y, (w + 2f) / scale, (h + 2f) / scale)
+ val unit = kotlin.math.hypot(trm.getValue(0, 0), trm.getValue(0, 1))
+ return if (unit > 0f) (w / scale) / unit else 0f
+ }
+}