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 a PDF's own text in place, in its original font

chethan6168abf23b1057f
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 a974af1..f05b201 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
@@ -298,6 +298,22 @@ internal fun PdfContinuousPage(
cap = StrokeCap.Round
)
}
+ is PdfMarkup.TextEditMarkup -> {
+ // Preview of an in-place edit: 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
+ val pad = markup.fontSize * 0.08f
+ drawRect(
+ c(markup.background),
+ Offset(markup.rect.left - pad, markup.rect.top - pad),
+ Size(markup.rect.width + pad * 2f, markup.rect.height + pad * 2f)
+ )
+ drawIntoCanvas { cv ->
+ val p = markup.previewPaint().apply { color = c(markup.color).toArgb() }
+ cv.nativeCanvas.drawText(markup.text, markup.rect.left, markup.baseline, p)
+ }
+ }
is PdfMarkup.ImageMarkup -> {
val r = Rect(min(markup.start.x, markup.end.x), min(markup.start.y, markup.end.y), max(markup.start.x, markup.end.x), max(markup.start.y, markup.end.y))
if (!markup.bitmap.isRecycled && markup.bitmap.width > 0) runCatching {
@@ -513,7 +529,8 @@ internal fun PdfContinuousPage(
is PdfMarkup.LineMarkup,
is PdfMarkup.StrokeMarkup,
is PdfMarkup.TextBlockHighlightMarkup,
- is PdfMarkup.TextBlockLineMarkup -> onSelectMarkup(idx)
+ is PdfMarkup.TextBlockLineMarkup,
+ is PdfMarkup.TextEditMarkup -> onSelectMarkup(idx)
else -> Unit
}
onShowControls()
@@ -769,6 +786,20 @@ internal fun PdfContinuousPage(
}
}
+ // 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 ->
+ PublishMarkupBar(
+ host = markupBar,
+ page = page,
+ token = selectedMarkupIndex,
+ anchor = te.rect,
+ onEdit = { onEditAnnotation(te.id) },
+ onDelete = { onDeleteMarkup(selectedMarkupIndex) },
+ onDismiss = { onSelectMarkup(-1) }
+ )
+ }
+
// Text highlights, underlines, and strike-throughs are precise OCR ranges, not
// transformable shapes. When one is tapped, expose the same clear destructive action
// used by the other professional markup tools.
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 bcfab3c..5a2301b 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
@@ -302,6 +302,58 @@ internal fun AnnotationEditorDialog(
}
}
+/**
+ * In-place editor for one line of the page's own text. The new text is written back in the line's
+ * original font on save (PdfTextEditor), so this is a single-line field, not a text box.
+ */
+@Composable
+internal fun TextEditDialog(
+ initialText: String,
+ original: String,
+ backdrop: LayerBackdrop,
+ canRevert: Boolean,
+ onDismiss: () -> Unit,
+ onRevert: () -> Unit,
+ onSave: (String) -> Unit
+) {
+ var text by remember { mutableStateOf(initialText) }
+ val focus = remember { FocusRequester() }
+ var shown by remember { mutableStateOf(false) }
+ LaunchedEffect(Unit) { shown = true; delay(260); runCatching { focus.requestFocus() } }
+ GlassDialog(
+ visible = shown,
+ onDismiss = onDismiss,
+ backdrop = backdrop,
+ title = stringResource(R.string.text_edit_title),
+ actions = {
+ if (canRevert) GlassDialogAction(stringResource(R.string.text_edit_revert), onRevert, destructive = true)
+ GlassDialogAction(stringResource(R.string.cancel), onDismiss)
+ 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))
+ Spacer(Modifier.height(10.dp))
+ GlassDialogField(
+ value = text,
+ onValueChange = { text = it.replace('\n', ' ') },
+ modifier = Modifier.fillMaxWidth(),
+ singleLine = true,
+ focusRequester = focus,
+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
+ keyboardActions = KeyboardActions(onDone = { onSave(text) })
+ )
+ if (text != original) {
+ Spacer(Modifier.height(8.dp))
+ BasicText(
+ stringResource(R.string.text_edit_original, original),
+ style = TextStyle(glassDialogInkSoft(), 11.sp),
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+}
+
/** Which file the viewer's Share action should hand off. */
internal enum class ShareFormat { ORIGINAL, PDF }
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 8fb5d8c..90b902e 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
@@ -112,6 +112,28 @@ internal sealed class PdfMarkup {
val fontSize: Float = 40f
) : PdfMarkup()
+ /**
+ * An in-place edit of one line of the page's OWN text (not a sticker): on screen the old line is
+ * covered by [background] and [text] drawn in the closest face at the line's real size and
+ * baseline; on export the old glyphs are removed from the PDF and the new text is written in the
+ * original font (PdfTextEditor). Geometry is content px like the other markups.
+ */
+ data class TextEditMarkup(
+ val id: Long,
+ val blockId: String,
+ val rect: Rect,
+ val baseline: Float,
+ val fontSize: Float,
+ val original: String,
+ val text: String,
+ val color: Color,
+ val background: Color,
+ val bold: Boolean,
+ val italic: Boolean,
+ val serif: Boolean,
+ val mono: Boolean
+ ) : PdfMarkup()
+
/** Sticky note. [anchor] is the content-space top-left of the icon. */
data class NoteMarkup(
val id: Long,
@@ -152,9 +174,28 @@ internal sealed class PdfMarkup {
val r = Rect(anchor.x - 8f, anchor.y - 8f, anchor.x + 40f, anchor.y + 40f)
r.contains(p)
}
+ is TextEditMarkup -> rect.inflate(8f).contains(p)
}
}
+/** The paint an in-place text edit previews with: the line's real size and closest typeface. */
+internal fun PdfMarkup.TextEditMarkup.previewPaint(): android.graphics.Paint =
+ android.graphics.Paint(android.graphics.Paint.ANTI_ALIAS_FLAG).apply {
+ textSize = fontSize
+ val family = when {
+ mono -> android.graphics.Typeface.MONOSPACE
+ serif -> android.graphics.Typeface.SERIF
+ else -> android.graphics.Typeface.SANS_SERIF
+ }
+ val style = when {
+ bold && italic -> android.graphics.Typeface.BOLD_ITALIC
+ bold -> android.graphics.Typeface.BOLD
+ italic -> android.graphics.Typeface.ITALIC
+ else -> android.graphics.Typeface.NORMAL
+ }
+ typeface = android.graphics.Typeface.create(family, style)
+ }
+
/** Recolourable free-form shapes (as opposed to images / OCR-anchored / text markups). */
internal fun PdfMarkup.isShape(): Boolean = this is PdfMarkup.StrokeMarkup ||
this is PdfMarkup.RectMarkup || this is PdfMarkup.OvalMarkup || this is PdfMarkup.LineMarkup
@@ -688,6 +729,20 @@ 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()
+ )
+ )
+ }
+ }
is PdfMarkup.NoteMarkup -> {
list.add(
ExportOverlay.NoteStamp(
@@ -720,3 +775,63 @@ internal fun recolorSignatureBitmap(source: Bitmap, colorArgb: Int): Bitmap {
result.setPixels(pixels, 0, source.width, 0, 0, source.width, source.height)
return result
}
+
+/** What the in-place text editor is editing: a line of [page]'s own text, maybe already edited. */
+internal data class TextEditTarget(
+ val page: Int,
+ val block: com.chethan616.clearpdf.ui.viewmodel.OcrTextBlock?,
+ val markupId: Long?
+)
+
+/**
+ * A new in-place edit of [block] (a digital-text line with [style]) at the page's current canvas
+ * size, with [text] as its replacement. The cover colour for the on-screen preview is sampled from
+ * the rendered page around the line, so coloured paper or a tinted table cell stays coloured.
+ */
+internal fun textEditMarkupFor(
+ block: com.chethan616.clearpdf.ui.viewmodel.OcrTextBlock,
+ style: com.kyant.pdfcore.text.PdfTextStyle,
+ canvas: androidx.compose.ui.geometry.Size,
+ bitmap: Bitmap?,
+ text: String
+): PdfMarkup.TextEditMarkup {
+ val w = canvas.width
+ val h = canvas.height
+ return PdfMarkup.TextEditMarkup(
+ id = System.nanoTime(),
+ blockId = block.id,
+ rect = Rect(block.left * w, block.top * h, block.right * w, block.bottom * h),
+ baseline = style.baselineNorm * h,
+ fontSize = style.emNorm * h,
+ original = block.text,
+ text = text,
+ color = Color(0xFF000000.toInt() or (style.rgb and 0xFFFFFF)),
+ background = samplePaper(bitmap, block),
+ bold = style.bold,
+ italic = style.italic,
+ serif = style.serif,
+ mono = style.mono
+ )
+}
+
+/** The colour most samples just outside the line agree on — the paper behind it. */
+private fun samplePaper(bitmap: Bitmap?, b: com.chethan616.clearpdf.ui.viewmodel.OcrTextBlock): Color {
+ if (bitmap == null || bitmap.isRecycled || bitmap.width <= 0 || bitmap.height <= 0) return Color.White
+ val bw = bitmap.width
+ val bh = bitmap.height
+ val dx = 0.006f
+ val dy = 0.004f
+ val cx = (b.left + b.right) / 2f
+ val points = listOf(
+ b.left - dx to b.top, b.left - dx to b.bottom, b.right + dx to b.top, b.right + dx to b.bottom,
+ cx to b.top - dy, cx to b.bottom + dy, b.left to b.top - dy, b.right to b.bottom + dy
+ )
+ val samples = points.mapNotNull { (x, y) ->
+ val px = (x * bw).toInt()
+ val py = (y * bh).toInt()
+ if (px in 0 until bw && py in 0 until bh) runCatching { bitmap.getPixel(px, py) }.getOrNull() else null
+ }
+ if (samples.isEmpty()) return Color.White
+ val paper = samples.groupBy { it and 0xF0F0F0 }.maxByOrNull { it.value.size }!!.value.first()
+ return Color(paper or 0xFF000000.toInt())
+}
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 1cca5a0..ea66488 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
@@ -243,6 +243,8 @@ fun PdfViewerScreen(
var bookmarkedPages by remember { mutableStateOf<List<Int>>(emptyList()) }
// Annotation (text box / sticky note) editing
var editingAnnoId by remember { mutableStateOf<Long?>(null) }
+ // In-place edit of a line of the page's own text (Text tool tap on existing text).
+ var textEditTarget by remember { mutableStateOf<TextEditTarget?>(null) }
var editingAnnoPage by remember { mutableStateOf(0) }
var editingAnnoIsNote by remember { mutableStateOf(false) }
var annotationDraft by remember { mutableStateOf("") }
@@ -1144,10 +1146,27 @@ fun PdfViewerScreen(
onActiveToolChanged = { activeTool = it },
onActiveImageIdChanged = { activeImageId = it },
onPlaceText = { pt ->
- val id = System.nanoTime()
- getPageMarks(page).add(PdfMarkup.TextBoxMarkup(id, pt, "", currentColor, 40f))
- recordEdit(page)
- editingAnnoId = id; editingAnnoPage = page; editingAnnoIsNote = false; annotationDraft = ""
+ // One Text tool: tapping the page's own text edits that line in
+ // place (same font); tapping empty space places a new text box.
+ val canvas = pageCanvasSizes[page]
+ val hitLine = canvas?.takeIf { it.width > 0f && it.height > 0f }?.let { cs ->
+ val nx = pt.x / cs.width; val ny = pt.y / cs.height
+ state.ocrBlocksByPage[page].orEmpty().firstOrNull { b ->
+ b.style != null && nx >= b.left - 0.004f && nx <= b.right + 0.004f &&
+ ny >= b.top - 0.004f && ny <= b.bottom + 0.004f
+ }
+ }
+ if (hitLine != null) {
+ val existing = getPageMarks(page).firstOrNull {
+ it is PdfMarkup.TextEditMarkup && it.blockId == hitLine.id
+ } as? PdfMarkup.TextEditMarkup
+ textEditTarget = TextEditTarget(page, hitLine, existing?.id)
+ } else {
+ val id = System.nanoTime()
+ getPageMarks(page).add(PdfMarkup.TextBoxMarkup(id, pt, "", currentColor, 40f))
+ recordEdit(page)
+ editingAnnoId = id; editingAnnoPage = page; editingAnnoIsNote = false; annotationDraft = ""
+ }
activeTool = PdfEditTool.None; controlsVisible = true
},
onPlaceNote = { pt ->
@@ -1157,7 +1176,12 @@ fun PdfViewerScreen(
editingAnnoId = id; editingAnnoPage = page; editingAnnoIsNote = true; annotationDraft = ""
activeTool = PdfEditTool.None; controlsVisible = true
},
- onEditAnnotation = { id ->
+ onEditAnnotation = annotationEdit@{ id ->
+ (getPageMarks(page).firstOrNull { it is PdfMarkup.TextEditMarkup && it.id == id } as? PdfMarkup.TextEditMarkup)?.let { te ->
+ val block = state.ocrBlocksByPage[page].orEmpty().firstOrNull { it.id == te.blockId }
+ textEditTarget = TextEditTarget(page, block, te.id)
+ return@annotationEdit
+ }
val m = getPageMarks(page).firstOrNull {
(it is PdfMarkup.TextBoxMarkup && it.id == id) || (it is PdfMarkup.NoteMarkup && it.id == id)
}
@@ -1782,6 +1806,22 @@ fun PdfViewerScreen(
)
}
}
+ },
+ // Long-press a word → "Edit text": rewrite that line in place, in its own font.
+ editableLine = {
+ val ranges = textSelection.rangesByPage()
+ val single = ranges.entries.singleOrNull()?.takeIf { it.value.map { r -> r.blockId }.distinct().size == 1 }
+ single?.let { (pg, rs) ->
+ state.ocrBlocksByPage[pg].orEmpty().firstOrNull { it.id == rs.first().blockId && it.style != null }
+ ?.let { pg to it }
+ }
+ },
+ onEditText = { pg, block ->
+ val existing = getPageMarks(pg).firstOrNull {
+ it is PdfMarkup.TextEditMarkup && it.blockId == block.id
+ } as? PdfMarkup.TextEditMarkup
+ textSelection.clear()
+ textEditTarget = TextEditTarget(pg, block, existing?.id)
}
)
// A lambda, evaluated inside the toolbar: reading the selection here would recompose this
@@ -1838,6 +1878,47 @@ fun PdfViewerScreen(
}
)
+ // ── In-place edit of the page's own text ──
+ textEditTarget?.let { target ->
+ val list = getPageMarks(target.page)
+ val existing = target.markupId?.let { id ->
+ list.firstOrNull { it is PdfMarkup.TextEditMarkup && it.id == id } as? PdfMarkup.TextEditMarkup
+ }
+ val original = existing?.original ?: target.block?.text.orEmpty()
+ TextEditDialog(
+ initialText = existing?.text ?: original,
+ original = original,
+ backdrop = contentBackdrop,
+ canRevert = existing != null,
+ onDismiss = { textEditTarget = null },
+ onRevert = {
+ list.removeAll { it is PdfMarkup.TextEditMarkup && it.id == existing?.id }
+ recordEdit(target.page)
+ selectedAnnoPage = null; selectedAnnoIndex = -1
+ textEditTarget = null
+ },
+ onSave = { newText ->
+ if (existing != null) {
+ val i = list.indexOf(existing)
+ if (i >= 0) {
+ if (newText == existing.original) list.removeAt(i) else list[i] = existing.copy(text = newText)
+ recordEdit(target.page)
+ }
+ } else if (newText != original) {
+ val block = target.block
+ val style = block?.style
+ val canvas = pageCanvasSizes[target.page]
+ if (block != null && style != null && canvas != null) {
+ list.add(textEditMarkupFor(block, style, canvas, state.pageBitmaps.getOrNull(target.page), newText))
+ recordEdit(target.page)
+ }
+ }
+ selectedAnnoPage = null; selectedAnnoIndex = -1
+ textEditTarget = null
+ }
+ )
+ }
+
// ── Text / note editor (in-window, samples the real page backdrop) ──
editingAnnoId?.let { annoId ->
fun matches(m: PdfMarkup) =
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionToolbar.kt b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionToolbar.kt
index aa70ddf..a5504a8 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionToolbar.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/selection/PdfSelectionToolbar.kt
@@ -46,6 +46,7 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material.icons.rounded.CheckCircle
+import androidx.compose.material.icons.rounded.EditNote
import androidx.compose.material.icons.rounded.ContentCopy
import androidx.compose.material.icons.rounded.FormatColorReset
import androidx.compose.material.icons.rounded.FormatUnderlined
@@ -123,7 +124,10 @@ class PdfSelectionActions(
val onStrike: () -> Unit,
val onRemoveHighlight: () -> Unit,
val onSearch: () -> Unit,
- val onProcessText: (ComponentName) -> Unit
+ val onProcessText: (ComponentName) -> Unit,
+ /** The (page, line) the selection sits on when that line is editable digital text, else null. */
+ val editableLine: () -> Pair<Int, com.chethan616.clearpdf.ui.viewmodel.OcrTextBlock>? = { null },
+ val onEditText: (Int, com.chethan616.clearpdf.ui.viewmodel.OcrTextBlock) -> Unit = { _, _ -> }
)
/** Highlight palette: classic marker yellow first, then the design system's accents. */
@@ -297,14 +301,17 @@ fun PdfSelectionToolbar(
val moreL = stringResource(R.string.selection_more)
val backL = stringResource(R.string.back)
val colorL = stringResource(R.string.selection_highlight_color)
+ val editTextL = stringResource(R.string.text_edit_title)
fun act(block: () -> Unit): () -> Unit = {
haptics.performHapticFeedback(HapticFeedbackType.VirtualKey)
block()
}
+ val editLine = if (shown) actions.editableLine() else null
val items = buildList {
add(ToolbarItem("copy", copyL, Icons.Rounded.ContentCopy, onClick = act(actions.onCopy)))
+ if (editLine != null) add(ToolbarItem("edit", editTextL, Icons.Rounded.EditNote, onClick = act { actions.onEditText(editLine.first, editLine.second) }))
add(ToolbarItem("all", selectAllL, Icons.Rounded.SelectAll, onClick = act(actions.onSelectAll)))
add(ToolbarItem(
"hl", highlightL, Icons.Rounded.Highlight, badge = highlightColor,
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 7768cc3..80e7fc2 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
@@ -58,7 +58,9 @@ data class OcrTextBlock(
val right: Float,
val bottom: Float,
val charLefts: FloatArray = FloatArray(0),
- val charRights: FloatArray = FloatArray(0)
+ val charRights: FloatArray = FloatArray(0),
+ /** Typography of a digital-text line (null for OCR text): drives in-place editing. */
+ val style: com.kyant.pdfcore.text.PdfTextStyle? = null
)
/** A word- or line-precise selection inside one extracted text block. [end] is exclusive. */
@@ -126,6 +128,19 @@ sealed class ExportOverlay {
val fontSizeNorm: Float
) : 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).
+ */
+ data class TextReplace(
+ val left: Float,
+ val top: Float,
+ val right: Float,
+ val bottom: Float,
+ val text: String,
+ val backgroundArgb: Int
+ ) : ExportOverlay()
+
/** A real PDF sticky-note annotation anchored at [position] (top-left of icon). */
data class NoteStamp(
val position: NormalizedPoint,
@@ -752,6 +767,15 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
val pageW = (page.cropBox ?: page.mediaBox)?.width ?: return@forEach
val pageH = (page.cropBox ?: page.mediaBox)?.height ?: return@forEach
+ // 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)
+ }
+ if (textEdits.isNotEmpty()) {
+ runCatching { com.kyant.pdfcore.text.PdfTextEditor.applyEdits(pdDoc, pageIdx, textEdits) }
+ }
+
com.tom_roush.pdfbox.pdmodel.PDPageContentStream(
pdDoc, page,
com.tom_roush.pdfbox.pdmodel.PDPageContentStream.AppendMode.APPEND,
@@ -924,6 +948,9 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
cs.endText()
}
+ // Already applied to the content stream before this pass.
+ is ExportOverlay.TextReplace -> Unit
+
is ExportOverlay.NoteStamp -> {
// A real, clickable PDF sticky-note annotation.
val c = android.graphics.Color.valueOf(overlay.colorArgb)
@@ -1003,7 +1030,7 @@ class PdfViewerViewModel(private val openPdfUseCase: OpenPdfUseCase) : ViewModel
private fun PdfTextBlock.toOcrBlock() = OcrTextBlock(
id = id, text = text, left = left, top = top, right = right, bottom = bottom,
- charLefts = charLefts, charRights = charRights
+ charLefts = charLefts, charRights = charRights, style = style
)
/** All occurrences of [lower] in this block as tight normalized word rects (fallback: block rect). */
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 02a8637..bfe1d4d 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -322,6 +322,10 @@
<string name="anno_hint">Type here…</string>
<string name="anno_save">Save</string>
<string name="anno_text_size">Size</string>
+ <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="text_edit_original">Original: %1$s</string>
<string name="not_now">Not now</string>
<string name="dont_ask_again">Don\'t ask again</string>
<string name="settings_custom_directory">Custom Directory</string>
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
new file mode 100644
index 0000000..7cbd52d
--- /dev/null
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextEditor.kt
@@ -0,0 +1,441 @@
+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
+import com.tom_roush.pdfbox.cos.COSFloat
+import com.tom_roush.pdfbox.cos.COSName
+import com.tom_roush.pdfbox.cos.COSNumber
+import com.tom_roush.pdfbox.cos.COSString
+import com.tom_roush.pdfbox.pdfparser.PDFStreamParser
+import com.tom_roush.pdfbox.pdfwriter.ContentStreamWriter
+import com.tom_roush.pdfbox.pdmodel.PDDocument
+import com.tom_roush.pdfbox.pdmodel.PDPage
+import com.tom_roush.pdfbox.pdmodel.PDPageContentStream
+import com.tom_roush.pdfbox.pdmodel.common.PDStream
+import com.tom_roush.pdfbox.pdmodel.font.PDFont
+import com.tom_roush.pdfbox.pdmodel.font.PDType0Font
+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 java.io.ByteArrayInputStream
+import java.io.ByteArrayOutputStream
+import java.io.File
+
+/**
+ * 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.
+ */
+data class PdfTextEdit(
+ val left: Float,
+ val top: Float,
+ val right: Float,
+ val bottom: Float,
+ val newText: String,
+ val backgroundArgb: Int = 0xFFFFFFFF.toInt()
+)
+
+/**
+ * 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
+ * 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.
+ *
+ * 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.
+ */
+object PdfTextEditor {
+
+ fun applyEdits(doc: PDDocument, pageIndex: Int, edits: List<PdfTextEdit>) {
+ if (edits.isEmpty() || pageIndex !in 0 until doc.numberOfPages) return
+ val page = doc.getPage(pageIndex)
+ val box = page.cropBox ?: page.mediaBox ?: return
+ 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 recorder = GlyphRecorder().apply {
+ startPage = pageIndex + 1
+ endPage = pageIndex + 1
+ }
+ runCatching { recorder.getText(doc) }
+
+ 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)
+ 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)
+ }
+
+ // 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 }
+ var removedOk = false
+ if (toRemove.isNotEmpty() && tokens != null) {
+ removedOk = runCatching {
+ val out = removeGlyphs(tokens, operatorIndex, toRemove)
+ val stream = PDStream(doc)
+ stream.createOutputStream(COSName.FLATE_DECODE).use { ContentStreamWriter(it).writeTokens(out) }
+ page.setContents(stream)
+ true
+ }.getOrDefault(false)
+ }
+
+ // 2) Draw the replacements on top, in a fresh, state-isolated stream.
+ 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)
+ continue
+ }
+ drawLike(doc, cs, first, text, box.lowerLeftX, box.lowerLeftY)
+ }
+ }
+ }
+
+ // ── Glyph bookkeeping ─────────────────────────────────────────────────────────────────
+
+ 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 depth: Int, // form XObject nesting (0 = page content)
+ val tp: TextPosition,
+ val font: PDFont,
+ val tfs: Float, val tc: Float, val tw: Float, val th: Float,
+ val rgb: Int,
+ val renderMode: RenderingMode
+ )
+
+ private class GlyphRecorder : PDFTextStripper() {
+ val glyphs = ArrayList<Glyph>()
+ private var depth = 0
+ private var op = -1
+ private var str = -1
+ private var idx = 0
+
+ override fun processOperator(operator: Operator, operands: MutableList<COSBase>) {
+ if (depth == 0) { op++; str = -1 }
+ super.processOperator(operator, operands)
+ }
+
+ override fun showForm(form: PDFormXObject) {
+ depth++
+ try { super.showForm(form) } finally { depth-- }
+ }
+
+ override fun showText(string: ByteArray) {
+ if (depth == 0) { str++; idx = 0 }
+ super.showText(string)
+ }
+
+ override fun processTextPosition(text: TextPosition) {
+ 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,
+ tfs = ts.fontSize, tc = ts.characterSpacing, tw = ts.wordSpacing,
+ th = ts.horizontalScaling / 100f,
+ rgb = runCatching { gs.nonStrokingColor.toRGB() }.getOrDefault(0),
+ renderMode = ts.renderingMode
+ )
+ }
+ }
+
+ private val TextShowOps = setOf("Tj", "TJ", "'", "\"")
+
+ private fun parseTokens(page: PDPage): MutableList<Any> {
+ val parser = PDFStreamParser(page)
+ val out = ArrayList<Any>()
+ while (true) out += parser.parseNextToken() ?: break
+ return out
+ }
+
+ /**
+ * Rewrites every affected text-showing operator as a `TJ` whose removed glyphs are replaced by
+ * spacing numbers equal to their advance, so the rest of the run doesn't move.
+ */
+ private fun removeGlyphs(tokens: MutableList<Any>, operatorIndex: List<Int>, glyphs: List<Glyph>): MutableList<Any> {
+ val out = ArrayList(tokens)
+ val byOp = glyphs.groupBy { it.op }
+ // Right to left, so earlier token positions stay valid while later slices are replaced.
+ for (op in byOp.keys.sortedDescending()) {
+ val opTok = operatorIndex[op]
+ val operator = out[opTok] as Operator
+ var firstOperand = opTok
+ while (firstOperand > 0 && out[firstOperand - 1] !is Operator) firstOperand--
+ val operands = out.subList(firstOperand, opTok).toList()
+ val g0 = byOp.getValue(op).first()
+ val removed = byOp.getValue(op).map { it.str to it.idx }.toHashSet()
+
+ fun rebuild(s: COSString, strIdx: Int, into: MutableList<COSBase>) {
+ val input = ByteArrayInputStream(s.bytes)
+ val run = ByteArrayOutputStream()
+ var gi = 0
+ fun flush() {
+ if (run.size() > 0) { into += COSString(run.toByteArray()); run.reset() }
+ }
+ while (input.available() > 0) {
+ val before = input.available()
+ val code = g0.font.readCode(input)
+ val len = before - input.available()
+ val bytes = s.bytes.copyOfRange(s.bytes.size - before, s.bytes.size - before + len)
+ if ((strIdx to gi) in removed) {
+ flush()
+ val w0 = g0.font.getWidth(code)
+ val tw = if (len == 1 && code == 32) g0.tw else 0f
+ val adj = -(w0 + (g0.tc + tw) * 1000f / g0.tfs)
+ val last = into.lastOrNull()
+ if (last is COSNumber) into[into.lastIndex] = COSFloat(last.floatValue() + adj)
+ else into += COSFloat(adj)
+ } else {
+ run.write(bytes)
+ }
+ gi++
+ }
+ flush()
+ }
+
+ val array = COSArray()
+ val replacement = ArrayList<Any>()
+ when (operator.name) {
+ "TJ" -> {
+ val src = operands.lastOrNull() as? COSArray ?: continue
+ val items = ArrayList<COSBase>()
+ var strIdx = -1
+ for (i in 0 until src.size()) {
+ when (val it = src.getObject(i)) {
+ is COSString -> { strIdx++; rebuild(it, strIdx, items) }
+ is COSNumber -> {
+ val last = items.lastOrNull()
+ if (last is COSNumber) items[items.lastIndex] = COSFloat(last.floatValue() + it.floatValue())
+ else items += it
+ }
+ else -> items += it
+ }
+ }
+ items.forEach { array.add(it) }
+ replacement.add(array); replacement.add(Operator.getOperator("TJ"))
+ }
+ "Tj", "'" -> {
+ val s = operands.lastOrNull() as? COSString ?: continue
+ val items = ArrayList<COSBase>(); rebuild(s, 0, items); items.forEach { array.add(it) }
+ if (operator.name == "'") replacement.add(Operator.getOperator("T*"))
+ replacement.add(array); replacement.add(Operator.getOperator("TJ"))
+ }
+ "\"" -> {
+ if (operands.size < 3) continue
+ val s = operands[2] as? COSString ?: continue
+ val items = ArrayList<COSBase>(); rebuild(s, 0, items); items.forEach { array.add(it) }
+ replacement.add(operands[0]); replacement.add(Operator.getOperator("Tw"))
+ replacement.add(operands[1]); replacement.add(Operator.getOperator("Tc"))
+ replacement.add(Operator.getOperator("T*"))
+ replacement.add(array); replacement.add(Operator.getOperator("TJ"))
+ }
+ else -> continue
+ }
+ val slice = out.subList(firstOperand, opTok + 1)
+ slice.clear()
+ slice.addAll(replacement)
+ }
+ return out
+ }
+
+ // ── Drawing the replacement ───────────────────────────────────────────────────────────
+
+ /** 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
+ )
+ 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)
+ }
+ }
+
+ /** 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,
+ 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)
+ 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)
+ }
+
+ private fun coverOldLine(
+ cs: PDPageContentStream, e: PdfTextEdit, llx: Float, lly: Float, dispW: Float, dispH: Float, rotation: Int
+ ) {
+ if (rotation != 0) return
+ val bg = e.backgroundArgb
+ cs.saveGraphicsState()
+ cs.setNonStrokingColor((bg shr 16) and 0xFF, (bg shr 8) and 0xFF, bg and 0xFF)
+ val pad = (e.bottom - e.top) * dispH * 0.08f
+ cs.addRect(
+ llx + e.left * dispW - pad,
+ lly + (1f - e.bottom) * dispH - pad,
+ (e.right - e.left) * dispW + pad * 2,
+ (e.bottom - e.top) * dispH + pad * 2
+ )
+ cs.fill()
+ 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)
+ }
+ 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 ─────────────────────────────────────────────────────────────────────────────
+
+ /** Whether [font] can draw every character of [text] (embedded subsets often can't). */
+ private fun canShow(font: PDFont, text: String): Boolean = try {
+ if (font is PDType3Font || font.isVertical) false
+ else {
+ var ok = true
+ var i = 0
+ while (i < text.length && ok) {
+ val cp = text.codePointAt(i)
+ i += Character.charCount(cp)
+ val bytes = font.encode(String(Character.toChars(cp)))
+ if (cp != ' '.code) {
+ var code = 0
+ for (b in bytes) code = (code shl 8) or (b.toInt() and 0xFF)
+ if (font is PDVectorFont && !font.hasGlyph(code)) ok = false
+ else if (font.getWidth(code) <= 0f) ok = false
+ }
+ }
+ ok
+ }
+ } catch (_: Exception) {
+ false
+ }
+
+ private class Traits(val bold: Boolean, val italic: Boolean, val serif: Boolean, val mono: Boolean)
+
+ private fun traitsOf(font: PDFont?): Traits {
+ val name = (font?.name ?: "").substringAfter('+').lowercase()
+ 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 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/PdfTextService.kt b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
index cd5f5b9..7d64041 100644
--- a/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
+++ b/pdf-core/src/main/java/com/kyant/pdfcore/text/PdfTextService.kt
@@ -19,7 +19,24 @@ data class PdfTextBlock(
// Per-text-character normalized x bounds, parallel to [text]. Enable word-precise
// highlighting of a matched substring instead of the whole line.
val charLefts: FloatArray = FloatArray(0),
- val charRights: FloatArray = FloatArray(0)
+ val charRights: FloatArray = FloatArray(0),
+ /** How the line is drawn (from its first glyph) — lets an in-place edit preview match it. */
+ val style: PdfTextStyle? = null
+)
+
+/**
+ * A line's typography: [emNorm] is the font size and [baselineNorm] the baseline's y, both as
+ * fractions of the (display) page height; the traits drive the closest Android typeface.
+ */
+data class PdfTextStyle(
+ val fontName: String,
+ val emNorm: Float,
+ val baselineNorm: Float,
+ val rgb: Int,
+ val bold: Boolean,
+ val italic: Boolean,
+ val serif: Boolean,
+ val mono: Boolean
)
/** A search hit as a normalized rect around the exact matched word(s), not the whole line. */
@@ -95,7 +112,7 @@ class PdfTextServiceImpl : PdfTextService {
}
runCatching { stripper.getText(doc) }
- return groupPositionsIntoLines(stripper.positions, pageW, pageH, pageIndex)
+ return groupPositionsIntoLines(stripper.positions, pageW, pageH, pageIndex, stripper.colors)
}
/** Per-font ascent/descent as fractions of the em, cached for the page being grouped. */
@@ -138,7 +155,8 @@ class PdfTextServiceImpl : PdfTextService {
positions: List<TextPosition>,
pageWidth: Float,
pageHeight: Float,
- pageIndex: Int
+ pageIndex: Int,
+ colors: Map<TextPosition, Int> = emptyMap()
): List<PdfTextBlock> {
if (positions.isEmpty()) return emptyList()
synchronized(fontMetricsCache) { fontMetricsCache.clear() }
@@ -235,6 +253,7 @@ class PdfTextServiceImpl : PdfTextService {
val minY = byX.minOf { it.y - glyphAscent(it) }.coerceAtLeast(0f)
val maxY = byX.maxOf { it.y + glyphDescent(it) }
+ val first = byX.first()
PdfTextBlock(
id = "$pageIndex-$lineIdx",
text = text,
@@ -243,7 +262,8 @@ class PdfTextServiceImpl : PdfTextService {
right = (maxX / pageWidth).coerceIn(0f, 1f),
bottom = (maxY / pageHeight).coerceIn(0f, 1f),
charLefts = charLefts,
- charRights = charRights
+ charRights = charRights,
+ style = styleOf(first, pageHeight, colors[first] ?: 0)
)
}
}
@@ -271,11 +291,38 @@ fun PdfTextBlock.matchRects(lower: String, pageIndex: Int): List<PdfSearchMatch>
private class PositionCapturingStripper : PDFTextStripper() {
val positions = mutableListOf<TextPosition>()
+ /** Fill colour each glyph was drawn in (only known while the page is being processed). */
+ val colors = java.util.IdentityHashMap<TextPosition, Int>()
override fun processTextPosition(text: TextPosition) {
- if (!text.unicode.isNullOrBlank()) positions.add(text)
+ if (!text.unicode.isNullOrBlank()) {
+ positions.add(text)
+ runCatching { graphicsState.nonStrokingColor.toRGB() }.getOrNull()?.let { colors[text] = it }
+ }
}
}
+private fun styleOf(tp: TextPosition, pageHeight: Float, rgb: Int): PdfTextStyle? = runCatching {
+ val font = tp.font
+ val name = (font?.name ?: "").substringAfter('+')
+ val lower = name.lowercase()
+ val d = font?.fontDescriptor
+ val m = tp.textMatrix
+ val em = kotlin.math.hypot(m.getValue(1, 0), m.getValue(1, 1)).takeIf { it > 0f } ?: tp.fontSizeInPt
+ val mono = listOf("courier", "mono", "consol", "menlo").any { lower.contains(it) } || d?.isFixedPitch == true
+ PdfTextStyle(
+ fontName = name,
+ emNorm = em / pageHeight,
+ baselineNorm = tp.y / pageHeight,
+ rgb = rgb,
+ bold = listOf("bold", "black", "heavy", "semibold", "demi").any { lower.contains(it) } ||
+ d?.isForceBold == true || (d?.fontWeight ?: 400f) >= 600f,
+ italic = lower.contains("italic") || lower.contains("oblique") || d?.isItalic == true,
+ serif = !mono && !lower.contains("sans") && (d?.isSerif == true ||
+ listOf("times", "serif", "georgia", "garamond", "cambria", "book", "minion", "palatino", "baskerville").any { lower.contains(it) }),
+ mono = mono
+ )
+}.getOrNull()
+
/** Typical Latin face: ascent 0.80 em, descent 0.20 em. */
private val DefaultMetrics = floatArrayOf(0.80f, 0.20f)