pdf: fix some rendering quirks
- Commit
e3003a2ea39788c3e2ab6eb1e2a6da57e5af6e38- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-27 18:57 UTC (4 months ago)
- Parents
73db501
Diff
pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.ktindex c3648c6aae..2852a9990d 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/ui/SafePdfViewerScreen.kt@@ -16,6 +16,7 @@ import androidx.compose.foundation.gestures.detectDragGesturesAfterLongPress import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.gestures.rememberTransformableState import androidx.compose.foundation.gestures.transformable+import androidx.compose.runtime.rememberUpdatedState import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxWithConstraints@@ -953,6 +954,13 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) { .padding(innerPadding) .fillMaxSize() .onSizeChanged { viewportSize = it }+ .graphicsLayer {+ scaleX = zoom+ scaleY = zoom+ translationX = pan.x+ translationY = pan.y+ }+ .transformable(transformState, enabled = !editMode || tool == EditTool.SELECT), ) { when (val state = loadState) { LoadState.Loading -> CircularProgressIndicator(Modifier.align(Alignment.Center))@@ -962,15 +970,7 @@ fun SafePdfViewerScreen(uri: Uri, onBack: () -> Unit) { modifier = Modifier.align(Alignment.Center).padding(24.dp), ) is LoadState.Loaded -> LazyColumn(- Modifier- .fillMaxSize()- .graphicsLayer {- scaleX = zoom- scaleY = zoom- translationX = pan.x- translationY = pan.y- }- .transformable(transformState, enabled = !editMode || tool == EditTool.SELECT),+ Modifier.fillMaxSize(), state = listState, ) { items((0 until pageCount).toList()) { index ->@@ -1271,7 +1271,8 @@ private fun NonEditOverlay( ) { val context = LocalContext.current val density = LocalDensity.current- // Clickable link boxes.+ // Text selection underneath so link Boxes get hit-test priority.+ TextSelectionLayer(page = page, ch = ch, scale = scale) for (link in links) { val leftDp = with(density) { (link.x0 * scale).toDp() } val topDp = with(density) { (ch - link.y1 * scale).toDp() }@@ -1294,10 +1295,6 @@ private fun NonEditOverlay( }, ) }-- // Glyph-level text selection with draggable handles. Always available in- // regular view — long-press a page to start selecting (see TextSelectionLayer).- TextSelectionLayer(page = page, ch = ch, scale = scale) } /** A single selectable glyph in reading order, with its on-screen rect - stores String for ligatures fi etc. */@@ -1314,17 +1311,35 @@ private fun TextSelectionLayer(page: SafePdfPage, ch: Float, scale: Float) { val clipboard = androidx.compose.ui.platform.LocalClipboard.current val scope = rememberCoroutineScope() // Build ordered glyphs once per page/scale using accurate advance + Tz handling (Phase 7).- val glyphs = remember(page, scale, ch) {+ // v8: include bold/italic for accurate measured width so spacing/melting is correct.+ // pointerInput is keyed only on page identity to avoid cancelling gesture on scale change.+ val glyphs = remember(page, ch, scale) { val list = ArrayList<Triple<Float, Float, SelGlyph>>() // (orderY, orderX, glyph)- val tmpPaint = android.graphics.Paint()+ val tmpPaint = android.graphics.Paint().apply {+ isAntiAlias = true+ isSubpixelText = true+ isLinearText = true+ } for (prim in page.primitives) { if (prim !is PdfPrimitive.Text || prim.text.isEmpty()) continue+ val tfStyle = when {+ prim.isBold && prim.isItalic -> android.graphics.Typeface.BOLD_ITALIC+ prim.isBold -> android.graphics.Typeface.BOLD+ prim.isItalic -> android.graphics.Typeface.ITALIC+ else -> android.graphics.Typeface.NORMAL+ }+ tmpPaint.typeface = android.graphics.Typeface.create(android.graphics.Typeface.DEFAULT, tfStyle)+ tmpPaint.isFakeBoldText = prim.isBold+ tmpPaint.textSkewX = if (prim.isItalic) -0.25f else 0f+ tmpPaint.textScaleX = prim.hScale.coerceIn(0.2f, 4f) tmpPaint.textSize = prim.size * scale val textStr = prim.text // Rust emits one glyph per Text prim with `advance` = that glyph's // true device-space advance (from /Widths|/W, Tc/Tw/Tz). Use it for // both stepping and glyph width; fall back to measured width only for // multi-char runs (the font-less fallback path).+ // For styled text, measure with the same bold/italic paint so per-glyph+ // measured fallback matches visual, avoiding overlap "melting". val measuredTotal = if (textStr.isNotEmpty()) tmpPaint.measureText(textStr) else prim.size * 0.5f val perGlyphMeasured = if (textStr.isNotEmpty()) measuredTotal / textStr.length else prim.size * 0.5f * scale var curPxPage = prim.origin.x@@ -1361,15 +1376,17 @@ private fun TextSelectionLayer(page: SafePdfPage, ch: Float, scale: Float) { return best } + val latestGlyphs by rememberUpdatedState(glyphs)+ Canvas(- Modifier.fillMaxSize().pointerInput(glyphs) {+ Modifier.fillMaxSize().pointerInput(page) { detectDragGesturesAfterLongPress( onDragStart = { pos ->+ val g = latestGlyphs val r = range- // Grab an existing handle if the touch is near one, else start fresh.- if (r != null) {- val startG = glyphs[r.first]- val endG = glyphs[r.last]+ if (r != null && r.first in g.indices && r.last in g.indices) {+ val startG = g[r.first]+ val endG = g[r.last] val dStart = kotlin.math.hypot(startG.left - pos.x, startG.bottom - pos.y) val dEnd = kotlin.math.hypot(endG.right - pos.x, endG.bottom - pos.y) if (minOf(dStart, dEnd) < 60f) {@@ -1383,15 +1400,18 @@ private fun TextSelectionLayer(page: SafePdfPage, ch: Float, scale: Float) { }, onDrag = { change, _ -> change.consume()+ val g = latestGlyphs+ if (g.isEmpty()) return@detectDragGesturesAfterLongPress val i = nearest(change.position) val r = range ?: (i..i) range = if (dragEnd) minOf(r.first, i)..maxOf(r.first, i) else minOf(i, r.last)..maxOf(i, r.last) }, onDragEnd = {+ val g = latestGlyphs val r = range- if (r != null) {- val text = glyphs.subList(r.first, r.last + 1).joinToString("") { it.ch }+ if (r != null && g.isNotEmpty() && r.first in g.indices && r.last in g.indices) {+ val text = g.subList(r.first, r.last + 1).joinToString("") { it.ch } if (text.isNotBlank()) { scope.launch { clipboard.setClipEntry(androidx.compose.ui.platform.ClipEntry(android.content.ClipData.newPlainText(context.getString(R.string.text), text))) } android.widget.Toast.makeText(context, context.getString(R.string.copied), android.widget.Toast.LENGTH_SHORT).show()@@ -1453,32 +1473,59 @@ private fun EditOverlay( // Accumulated move delta for the selected annotation (screen space). var moveDelta by remember { mutableStateOf(Offset.Zero) } + // Keep annotation data stable for the gesture coroutine via updated states, so+ // the gesture is NOT cancelled when selected or annotations identity changes+ // (previously pointerInput(tool, selected, annotations) caused annotation drag+ // to cancel immediately after selecting at touchSlop threshold).+ val latestAnnotations by rememberUpdatedState(annotations)+ val latestSelected by rememberUpdatedState(selected)+ val latestToPage by rememberUpdatedState(toPage)+ val latestOnSelect by rememberUpdatedState(onSelect)+ val latestOnStartText by rememberUpdatedState(onStartText)+ val latestOnRequestImage by rememberUpdatedState(onRequestImage)+ val latestOnRequestNote by rememberUpdatedState(onRequestNote)+ val latestOnRequestCallout by rememberUpdatedState(onRequestCallout)+ val latestOnAddPolyPoint by rememberUpdatedState(onAddPolyPoint)+ val latestOnCreated by rememberUpdatedState(onCreated)+ val latestOnEdited by rememberUpdatedState(onEdited)+ val latestOnMoved by rememberUpdatedState(onMoved)+ val latestDocument by rememberUpdatedState(document)+ val latestScope by rememberUpdatedState(scope)+ val latestScale by rememberUpdatedState(scale)+ val latestShape by rememberUpdatedState(shape)+ val latestMarkup by rememberUpdatedState(markup)+ val latestColor by rememberUpdatedState(color)+ val latestStroke by rememberUpdatedState(strokeWidth)+ val currentTool by rememberUpdatedState(tool)+ fun annotAt(screen: Offset): SafeAnnotation? {- val p = toPage(screen)- return annotations.lastOrNull { p.x in it.x0..it.x1 && p.y in it.y0..it.y1 }+ val p = latestToPage(screen)+ return latestAnnotations.lastOrNull { p.x in it.x0..it.x1 && p.y in it.y0..it.y1 } } - val gestures = Modifier.pointerInput(tool, selected, annotations) {+ val gestures = Modifier.pointerInput(currentTool, index) { awaitEachGesture { val down = awaitFirstDown(requireUnconsumed = false) val start = down.position- // With Select, only capture the gesture when it starts on an annotation- // (a move). On empty space we leave it unconsumed so the list scrolls.- val selectMove = tool == EditTool.SELECT && annotAt(start) != null+ val hitAtDown = annotAt(start)+ val selectMove = currentTool == EditTool.SELECT && hitAtDown != null val blockScroll =- tool == EditTool.HIGHLIGHT || tool == EditTool.MARKUP || tool == EditTool.SHAPE ||- tool == EditTool.LINE || tool == EditTool.CALLOUT || tool == EditTool.REDACT ||- tool == EditTool.DRAW || selectMove- if (blockScroll) {+ currentTool == EditTool.HIGHLIGHT || currentTool == EditTool.MARKUP || currentTool == EditTool.SHAPE ||+ currentTool == EditTool.LINE || currentTool == EditTool.CALLOUT || currentTool == EditTool.REDACT ||+ currentTool == EditTool.DRAW || selectMove+ // SELECT defers consume until dragging to allow pinch-zoom over annotation+ if (blockScroll && currentTool != EditTool.SELECT) { down.consume()- dragStart = start- dragCurrent = start- if (tool == EditTool.DRAW) inkPoints = listOf(start) }- if (tool == EditTool.SELECT) moveDelta = Offset.Zero+ dragStart = start+ dragCurrent = start+ if (currentTool == EditTool.DRAW) inkPoints = listOf(start)+ if (currentTool == EditTool.SELECT) moveDelta = Offset.Zero var dragging = false var lastPos = start+ var draggedId: Long? = hitAtDown?.id+ var draggedInitRect: List<Float>? = hitAtDown?.let { listOf(it.x0, it.y0, it.x1, it.y1) } while (true) { val event = awaitPointerEvent() val change = event.changes.firstOrNull { it.id == down.id } ?: break@@ -1486,13 +1533,17 @@ private fun EditOverlay( val pos = change.position if (!dragging && (pos - start).getDistance() > viewConfiguration.touchSlop) { dragging = true- if (selectMove) onSelect(annotAt(start)?.id)+ if (selectMove) {+ latestOnSelect(draggedId)+ change.consume()+ down.consume()+ } } if (dragging) { // Don't consume Select drags on empty space, so they scroll.- val consume = tool != EditTool.SELECT || selectMove+ val consume = currentTool != EditTool.SELECT || selectMove if (consume) change.consume()- when (tool) {+ when (currentTool) { EditTool.HIGHLIGHT, EditTool.MARKUP, EditTool.SHAPE, EditTool.LINE, EditTool.CALLOUT, EditTool.REDACT -> dragCurrent = pos EditTool.DRAW -> { dragCurrent = pos; inkPoints = inkPoints + pos } EditTool.SELECT -> if (selectMove) moveDelta += (pos - lastPos)@@ -1503,28 +1554,29 @@ private fun EditOverlay( } if (!dragging) {- when (tool) {+ when (currentTool) { EditTool.TEXT -> {- val p = toPage(start)- onStartText(+ val p = latestToPage(start)+ latestOnStartText( TextSession( page = index, origin = p, size = 14f,- color = color.toArgb(),+ color = latestColor.toArgb(), annotId = null, value = TextFieldValue("Text", TextRange(0, 4)), ) ) }- EditTool.IMAGE -> onRequestImage(toPage(start))- EditTool.NOTE -> onRequestNote(toPage(start))- EditTool.POLYLINE, EditTool.BEZIER -> onAddPolyPoint(toPage(start))+ EditTool.IMAGE -> latestOnRequestImage(latestToPage(start))+ EditTool.NOTE -> latestOnRequestNote(latestToPage(start))+ EditTool.POLYLINE, EditTool.BEZIER -> latestOnAddPolyPoint(latestToPage(start)) EditTool.SELECT -> { val hit = annotAt(start)- if (hit != null && hit.id == selected && hit.subtype == 1) {+ val sel = latestSelected+ if (hit != null && hit.id == sel && hit.subtype == 1) { val sz = ((hit.y1 - hit.y0) / 1.3f).coerceIn(6f, 72f)- onStartText(+ latestOnStartText( TextSession( page = index, origin = Offset(hit.x0, hit.y1),@@ -1535,7 +1587,7 @@ private fun EditOverlay( ) ) } else {- onSelect(hit?.id)+ latestOnSelect(hit?.id) } } else -> {}@@ -1543,78 +1595,81 @@ private fun EditOverlay( } else { val s = dragStart val e = dragCurrent- when (tool) {+ val doc = latestDocument+ val scp = latestScope+ when (currentTool) { EditTool.HIGHLIGHT -> if (s != null && e != null) {- val a = toPage(s); val b = toPage(e)- scope.launch {- val id = document.addHighlight(index, a.x, a.y, b.x, b.y, color.toArgb())- onCreated(id); onEdited()+ val a = latestToPage(s); val b = latestToPage(e)+ scp.launch {+ val id = doc.addHighlight(index, a.x, a.y, b.x, b.y, latestColor.toArgb())+ latestOnCreated(id); latestOnEdited() } } EditTool.MARKUP -> if (s != null && e != null) {- val a = toPage(s); val b = toPage(e)- scope.launch {- val id = if (markup == MarkupKind.HIGHLIGHT) {- document.addHighlight(index, a.x, a.y, b.x, b.y, color.toArgb())+ val a = latestToPage(s); val b = latestToPage(e)+ scp.launch {+ val mk = latestMarkup+ val id = if (mk == MarkupKind.HIGHLIGHT) {+ doc.addHighlight(index, a.x, a.y, b.x, b.y, latestColor.toArgb()) } else {- val kind = when (markup) {+ val kind = when (mk) { MarkupKind.STRIKEOUT -> 1 MarkupKind.SQUIGGLY -> 2 else -> 0 }- document.addTextMarkup(index, a.x, a.y, b.x, b.y, color.toArgb(), kind)+ doc.addTextMarkup(index, a.x, a.y, b.x, b.y, latestColor.toArgb(), kind) }- onCreated(id); onEdited()+ latestOnCreated(id); latestOnEdited() } } EditTool.CALLOUT -> if (s != null && e != null) {- onRequestCallout(toPage(s), toPage(e))+ latestOnRequestCallout(latestToPage(s), latestToPage(e)) } EditTool.SHAPE -> if (s != null && e != null) { val rect = Rect(minOf(s.x, e.x), minOf(s.y, e.y), maxOf(s.x, e.x), maxOf(s.y, e.y))- val lineWidth = if (shape.isFill) 0f else strokeWidth- when (shape.geom) {+ val shp = latestShape+ val lineWidth = if (shp.isFill) 0f else latestStroke+ when (shp.geom) { ShapeGeom.RECT -> {- val a = toPage(Offset(rect.left, rect.top)); val b = toPage(Offset(rect.right, rect.bottom))- scope.launch {- val id = document.addRect(index, a.x, a.y, b.x, b.y, color.toArgb(), lineWidth, shape.isFill)- onCreated(id); onEdited()+ val a = latestToPage(Offset(rect.left, rect.top)); val b = latestToPage(Offset(rect.right, rect.bottom))+ scp.launch {+ val id = doc.addRect(index, a.x, a.y, b.x, b.y, latestColor.toArgb(), lineWidth, shp.isFill)+ latestOnCreated(id); latestOnEdited() } } ShapeGeom.OVAL -> {- val a = toPage(Offset(rect.left, rect.top)); val b = toPage(Offset(rect.right, rect.bottom))- scope.launch {- val id = document.addOval(index, a.x, a.y, b.x, b.y, color.toArgb(), lineWidth, shape.isFill)- onCreated(id); onEdited()+ val a = latestToPage(Offset(rect.left, rect.top)); val b = latestToPage(Offset(rect.right, rect.bottom))+ scp.launch {+ val id = doc.addOval(index, a.x, a.y, b.x, b.y, latestColor.toArgb(), lineWidth, shp.isFill)+ latestOnCreated(id); latestOnEdited() } } ShapeGeom.POLYGON -> {- val unit = shape.unitPolygon()+ val unit = shp.unitPolygon() val flat = FloatArray(unit.size * 2) unit.forEachIndexed { i, u ->- val pp = toPage(mapUnit(u, rect)); flat[i * 2] = pp.x; flat[i * 2 + 1] = pp.y+ val pp = latestToPage(mapUnit(u, rect)); flat[i * 2] = pp.x; flat[i * 2 + 1] = pp.y }- scope.launch {- val id = document.addPoly(index, flat, color.toArgb(), lineWidth, shape.isFill, closed = true)- onCreated(id); onEdited()+ scp.launch {+ val id = doc.addPoly(index, flat, latestColor.toArgb(), lineWidth, shp.isFill, closed = true)+ latestOnCreated(id); latestOnEdited() } } } } EditTool.LINE -> if (s != null && e != null) {- val a = toPage(s); val b = toPage(e)- scope.launch {- val id = document.addPoly(index, floatArrayOf(a.x, a.y, b.x, b.y), color.toArgb(), strokeWidth, fill = false, closed = false)- onCreated(id); onEdited()+ val a = latestToPage(s); val b = latestToPage(e)+ scp.launch {+ val id = doc.addPoly(index, floatArrayOf(a.x, a.y, b.x, b.y), latestColor.toArgb(), latestStroke, fill = false, closed = false)+ latestOnCreated(id); latestOnEdited() } } EditTool.REDACT -> if (s != null && e != null) {- val a = toPage(Offset(minOf(s.x, e.x), minOf(s.y, e.y)))- val b = toPage(Offset(maxOf(s.x, e.x), maxOf(s.y, e.y)))- scope.launch {- // Marked redaction box; "Apply redactions" removes the content beneath.- val id = document.addRedaction(index, a.x, a.y, b.x, b.y)- onCreated(id); onEdited()+ val a = latestToPage(Offset(minOf(s.x, e.x), minOf(s.y, e.y)))+ val b = latestToPage(Offset(maxOf(s.x, e.x), maxOf(s.y, e.y)))+ scp.launch {+ val id = doc.addRedaction(index, a.x, a.y, b.x, b.y)+ latestOnCreated(id); latestOnEdited() } } EditTool.DRAW -> {@@ -1622,27 +1677,39 @@ private fun EditOverlay( if (pts.size >= 2) { val flat = FloatArray(pts.size * 2) pts.forEachIndexed { i, o ->- val pp = toPage(o); flat[i * 2] = pp.x; flat[i * 2 + 1] = pp.y+ val pp = latestToPage(o); flat[i * 2] = pp.x; flat[i * 2 + 1] = pp.y }- scope.launch {- val id = document.addInk(index, color.toArgb(), strokeWidth, flat)- onCreated(id); onEdited()+ scp.launch {+ val id = doc.addInk(index, latestColor.toArgb(), latestStroke, flat)+ latestOnCreated(id); latestOnEdited() } } } EditTool.SELECT -> if (selectMove) {- val id = selected- val a = annotations.firstOrNull { it.id == id }- if (id != null && a != null) {- val dx = moveDelta.x / scale- val dy = -moveDelta.y / scale+ val id = draggedId+ if (id != null) {+ val dx = moveDelta.x / latestScale+ val dy = -moveDelta.y / latestScale if (dx != 0f || dy != 0f) {- val oldR = listOf(a.x0, a.y0, a.x1, a.y1)- val newR = listOf(a.x0 + dx, a.y0 + dy, a.x1 + dx, a.y1 + dy)- scope.launch {- document.moveAnnotation(index, id, newR[0], newR[1], newR[2], newR[3])- onMoved(id, oldR, newR)- onEdited()+ val initR = draggedInitRect+ if (initR != null) {+ val newR = listOf(initR[0] + dx, initR[1] + dy, initR[2] + dx, initR[3] + dy)+ scp.launch {+ doc.moveAnnotation(index, id, newR[0], newR[1], newR[2], newR[3])+ latestOnMoved(id, initR, newR)+ latestOnEdited()+ }+ } else {+ val a = latestAnnotations.firstOrNull { it.id == id }+ if (a != null) {+ val oldR = listOf(a.x0, a.y0, a.x1, a.y1)+ val newR = listOf(a.x0 + dx, a.y0 + dy, a.x1 + dx, a.y1 + dy)+ scp.launch {+ doc.moveAnnotation(index, id, newR[0], newR[1], newR[2], newR[3])+ latestOnMoved(id, oldR, newR)+ latestOnEdited()+ }+ } } } }@@ -1652,14 +1719,14 @@ private fun EditOverlay( } dragStart = null dragCurrent = null- if (tool == EditTool.DRAW) inkPoints = emptyList()+ if (currentTool == EditTool.DRAW) inkPoints = emptyList() moveDelta = Offset.Zero } } Canvas(Modifier.fillMaxSize().then(gestures)) { // Selection highlight.- val sel = annotations.firstOrNull { it.id == selected }+ val sel = latestAnnotations.firstOrNull { it.id == latestSelected } if (sel != null) { val left = sel.x0 * scale + moveDelta.x val top = ch - sel.y1 * scale + moveDelta.y@@ -2148,10 +2215,14 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) { val textPaint = android.graphics.Paint().apply { isAntiAlias = true isDither = true+ isSubpixelText = true+ isLinearText = true } val textStrokePaint = android.graphics.Paint().apply { isAntiAlias = true isDither = true+ isSubpixelText = true+ isLinearText = true style = android.graphics.Paint.Style.STROKE } val imagePaint = android.graphics.Paint().apply {@@ -2277,6 +2348,31 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) { val rm = prim.renderMode val isStrokeOnly = prim.strokeColor != null && prim.color == prim.strokeColor + // v8: font style synthesis from Rust — BaseFont / FontDescriptor bold/italic+ // This fixes bolding/italics not being applied. We synthesize via Typeface+ // + fakeBold/skew because PDF uses separate fonts for bold, which we don't+ // rasterize as outlines. Also honor Tz (hScale) via Paint.textScaleX.+ val tfStyle = when {+ prim.isBold && prim.isItalic -> android.graphics.Typeface.BOLD_ITALIC+ prim.isBold -> android.graphics.Typeface.BOLD+ prim.isItalic -> android.graphics.Typeface.ITALIC+ else -> android.graphics.Typeface.NORMAL+ }+ val tf = android.graphics.Typeface.create(android.graphics.Typeface.DEFAULT, tfStyle)+ textPaint.typeface = tf+ textPaint.isFakeBoldText = prim.isBold+ textPaint.textSkewX = if (prim.isItalic) -0.25f else 0f+ textPaint.textScaleX = prim.hScale.coerceIn(0.2f, 4f)+ textStrokePaint.typeface = tf+ textStrokePaint.isFakeBoldText = prim.isBold+ textStrokePaint.textSkewX = textPaint.textSkewX+ textStrokePaint.textScaleX = textPaint.textScaleX+ glyphPathPaint.typeface = tf+ glyphPathPaint.textSize = ts+ glyphPathPaint.textSkewX = textPaint.textSkewX+ glyphPathPaint.textScaleX = textPaint.textScaleX+ glyphPathPaint.isFakeBoldText = prim.isBold+ // Paint the glyphs unless this is a clip-only run (Tr 7). if (rm != 7) { if (prim.strokeColor != null && prim.strokeWidth > 0f) {@@ -2297,9 +2393,9 @@ internal fun DrawScope.drawSafePage(page: SafePdfPage) { } // Accumulate glyph outlines for text-clip render modes (Tr 4-7),- // applied at the following TextClipApply marker.+ // applied at the following TextClipApply marker. Use styled glyphPathPaint+ // so clip matches bold/italic visual. if (rm in 4..7) {- glyphPathPaint.textSize = ts tmpGlyphPath.reset() glyphPathPaint.getTextPath(prim.text, 0, prim.text.length, origin.x, origin.y, tmpGlyphPath) textClipPath.addPath(tmpGlyphPath)
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.ktindex ea244cc5a8..f6486d7c9f 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfModels.kt@@ -27,6 +27,7 @@ sealed interface PdfPrimitive { * A run of text with its baseline origin, on-page size and color. Optional * stroke for Tr modes 1,2,5,6. [renderMode] is the PDF text render mode (Tr): * 0 fill, 1 stroke, 2 fill+stroke, 3 invisible, 4-6 = 0-2 plus clip, 7 clip.+ * v8 adds isBold/isItalic/hScale recovered from font BaseFont/FontDescriptor. */ data class Text( val origin: Offset,@@ -38,6 +39,9 @@ sealed interface PdfPrimitive { val advance: Float = size * 0.5f * text.length, val renderMode: Int = 0, val blend: BlendMode = BlendMode.Normal,+ val isBold: Boolean = false,+ val isItalic: Boolean = false,+ val hScale: Float = 1f, ) : PdfPrimitive /**
pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt
diff --git a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.ktindex 42f09d9f46..9de937d489 100644--- a/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt+++ b/pdf/src/main/java/com/vayunmathur/pdf/util/SafePdfParser.kt@@ -8,13 +8,13 @@ import java.nio.ByteOrder * Decodes the compact little-endian primitive buffer produced by the native * renderer ([PdfNative.renderPage]) into a [SafePdfPage]. *- * Wire format v6 (must stay in sync with `pdf/rust/src/wire.rs`):+ * Wire format v8 (must stay in sync with `pdf/rust/src/wire.rs`): * ```- * header: u32 MAGIC=0x50444657, u32 VERSION=6, f32 pageWidth, f32 pageHeight, u32 primitiveCount+ * header: u32 MAGIC=0x50444657, u32 VERSION=8, f32 pageWidth, f32 pageHeight, u32 primitiveCount * Legacy v1 fallback: header is f32 W,H,u32 count (no magic)- * v2..v5 fallbacks: same layout with fewer trailing per-primitive fields+ * v2..v7 fallbacks: same layout with fewer trailing per-primitive fields * per primitive: u8 tag, then payload- * 1 Text: f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8 bytes], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5)+ * 1 Text: f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8 bytes], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5), f32 advance (v7), u8 fontFlags (v8 bit0 bold bit1 italic), f32 hScale (v8) * 2 Fill: u32 argb, u8 evenOdd, u16 nContours, [u16 nPts, [f32 x,y]...]... (v6), u8 blend (v5) * 3 Stroke: u32 argb, f32 width, u8 nDash, [f32 dash]..., f32 phase, u8 cap, u8 join, f32 miter, u16 nPts, [f32 x, f32 y]..., u8 blend (v5) * 4 Image: 6*f32 ctm, u32 w, u32 h, u8 format, u32 len, [bytes]@@ -28,7 +28,7 @@ import java.nio.ByteOrder * 12 SoftMaskPop: empty (v5) * ``` * Pure function -> unit-testable with no Android dependencies beyond [Offset].- * Enforces count guards to avoid OOM: max 50k primitives.+ * Enforces count guards to avoid OOM: max 50k primitives. v8 adds font style. */ object SafePdfParser { @@ -51,12 +51,13 @@ object SafePdfParser { private const val PATHOP_CLOSE = 3 const val WIRE_MAGIC: Int = 0x50444657 // 'PDFW' little-endian as u32- const val WIRE_VERSION: Int = 7+ const val WIRE_VERSION: Int = 8 private const val WIRE_VERSION_V2 = 2 private const val WIRE_VERSION_V4 = 4 private const val WIRE_VERSION_V5 = 5 private const val WIRE_VERSION_V6 = 6 private const val WIRE_VERSION_V7 = 7+ private const val WIRE_VERSION_V8 = 8 const val MAX_PRIMITIVES = 50000 const val MAX_ANNOTATIONS = 10000 @@ -97,6 +98,7 @@ object SafePdfParser { val isV5 = wireVersion >= WIRE_VERSION_V5 val isV6 = wireVersion >= WIRE_VERSION_V6 val isV7 = wireVersion >= WIRE_VERSION_V7+ val isV8 = wireVersion >= WIRE_VERSION_V8 // Accept v1 (legacy), v2, v3 and v4. Newer versions are tolerated via // forward-compat parsing as long as the tags are known. if (wireVersion !in 1..WIRE_VERSION) {@@ -156,6 +158,20 @@ object SafePdfParser { } else { size * 0.5f * txt.length.coerceAtLeast(1) }+ val isBold: Boolean+ val isItalic: Boolean+ val hScale: Float+ if (isV8) {+ if (buf.remaining() < 5) throw IllegalArgumentException("Text v8 fontFlags truncated")+ val fontFlags = buf.get().toInt() and 0xFF+ isBold = fontFlags and 1 != 0+ isItalic = fontFlags and 2 != 0+ hScale = buf.float+ } else {+ isBold = false+ isItalic = false+ hScale = 1f+ } primitives.add( PdfPrimitive.Text( origin = Offset(x, y),@@ -167,6 +183,9 @@ object SafePdfParser { advance = adv, renderMode = renderMode, blend = blend,+ isBold = isBold,+ isItalic = isItalic,+ hScale = hScale, ) ) }
pdf/src/main/rust/src/draw.rs
diff --git a/pdf/src/main/rust/src/draw.rs b/pdf/src/main/rust/src/draw.rsindex 55959b4179..db69a6a182 100644--- a/pdf/src/main/rust/src/draw.rs+++ b/pdf/src/main/rust/src/draw.rs@@ -130,6 +130,9 @@ pub(crate) fn show_string( advance: size, render_mode: gs.render_mode as u8, blend: gs.blend_mode,+ is_bold: false,+ is_italic: false,+ h_scale: th as f32, }); } }@@ -171,6 +174,8 @@ pub(crate) fn show_string( let base_adv = fi.width(code) * tfs; let _ = base_adv; let glyph_device_adv = (glyph_advance_user * x_scale) as f32;+ let bold = fi.style.bold;+ let italic = fi.style.italic; if prims.len() < MAX_PRIMITIVES { if has_fill { prims.push(Prim::Text {@@ -184,6 +189,9 @@ pub(crate) fn show_string( stroke_width: if has_stroke { Some(device_stroke_w) } else { None }, render_mode: rm, blend: gs.blend_mode,+ is_bold: bold,+ is_italic: italic,+ h_scale: th as f32, }); } else if has_stroke { prims.push(Prim::Text {@@ -197,6 +205,9 @@ pub(crate) fn show_string( stroke_width: Some(device_stroke_w), render_mode: rm, blend: gs.blend_mode,+ is_bold: bold,+ is_italic: italic,+ h_scale: th as f32, }); } else if clip_only { // Mode 7: no paint, but carry the glyph so Kotlin can add@@ -212,6 +223,9 @@ pub(crate) fn show_string( stroke_width: None, render_mode: 7, blend: gs.blend_mode,+ is_bold: bold,+ is_italic: italic,+ h_scale: th as f32, }); } }
pdf/src/main/rust/src/fonts.rs
diff --git a/pdf/src/main/rust/src/fonts.rs b/pdf/src/main/rust/src/fonts.rsindex 0bb32aee68..463007afbd 100644--- a/pdf/src/main/rust/src/fonts.rs+++ b/pdf/src/main/rust/src/fonts.rs@@ -1,5 +1,15 @@ use crate::*; +#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct FontStyle {+ pub(crate) bold: bool,+ pub(crate) italic: bool,+}++impl Default for FontStyle {+ fn default() -> Self { Self { bold: false, italic: false } }+}+ pub(crate) struct FontInfo { /// Type0 (Identity-H) fonts use 2-byte codes; simple fonts use 1 byte. pub(crate) two_byte: bool,@@ -17,6 +27,10 @@ pub(crate) struct FontInfo { pub(crate) default_width: f64, /// Type 3 font data (glyph CharProc content streams), if this is a Type 3 font. pub(crate) t3: Option<Type3Font>,+ /// Synthetic font style recovered from BaseFont name + FontDescriptor.+ pub(crate) style: FontStyle,+ /// Descriptive base font name for fallback shaping (optional).+ pub(crate) base_font: String, } /// Type 3 font: glyphs are content streams drawn in glyph space, mapped to text@@ -36,7 +50,12 @@ impl FontInfo { let mut i = 0; while i + 1 < bytes.len() { let code = ((bytes[i] as u32) << 8) | bytes[i + 1] as u32;- f(code, false);+ // For Identity-H, space is often 0x0020; we still need word_spacing.+ // is_space here means unicode space check after decoding would be better,+ // but we approximate by code == 0x20 or ToUnicode maps to ' '.+ let is_space = code == 32 ||+ self.to_unicode.as_ref().and_then(|m| m.get(&code)).map(|s| s == " ").unwrap_or(false);+ f(code, is_space); i += 2; } } else {@@ -154,6 +173,66 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { m }; + // --- Font style detection for bold/italic synthesis ---+ let base_font_name = font.get(b"BaseFont").ok().and_then(|o| o.as_name().ok())+ .map(|n| String::from_utf8_lossy(n).to_string())+ .or_else(|| {+ // Try descendant for Type0+ font.get(b"DescendantFonts").ok().and_then(|o| deref(doc, o))+ .and_then(|o| match o { Object::Array(a) => a.first(), _ => None })+ .and_then(|o| deref(doc, o))+ .and_then(|o| o.as_dict().ok())+ .and_then(|d| d.get(b"BaseFont").ok())+ .and_then(|o| o.as_name().ok())+ .map(|n| String::from_utf8_lossy(n).to_string())+ })+ .unwrap_or_default();++ let fd = font.get(b"FontDescriptor").ok().and_then(|o| deref(doc, o))+ .and_then(|o| o.as_dict().ok()).cloned()+ .or_else(|| {+ // For Type0, try descendant's FontDescriptor+ font.get(b"DescendantFonts").ok().and_then(|o| deref(doc, o))+ .and_then(|o| match o { Object::Array(a) => a.first(), _ => None })+ .and_then(|o| deref(doc, o))+ .and_then(|o| o.as_dict().ok())+ .and_then(|d| d.get(b"FontDescriptor").ok())+ .and_then(|o| deref(doc, o))+ .and_then(|o| o.as_dict().ok())+ .cloned()+ });++ let mut bold = false;+ let mut italic = false;+ let lower = base_font_name.to_lowercase();+ if lower.contains("bold") || lower.contains("black") || lower.contains("heavy") {+ bold = true;+ }+ if lower.contains("italic") || lower.contains("oblique") || lower.contains("slanted") {+ italic = true;+ }+ if let Some(ref desc) = fd {+ if let Some(flags) = desc.get(b"Flags").ok().and_then(num) {+ let f = flags as i64;+ // Bit 18 (1<<18 = 262144) = Italic per PDF spec 9.8.2+ if f & (1<<18) != 0 || f & 64 != 0 { italic = true; } // 64 is common non-spec but some generators+ // There is no bold flag but some files use bit 6? Actually force bold is 18? We'll rely on StemV/Weight+ }+ if let Some(angle) = desc.get(b"ItalicAngle").ok().and_then(num) {+ if angle.abs() > 0.5 { italic = true; }+ }+ if let Some(weight) = desc.get(b"FontWeight").ok().and_then(num) {+ if weight >= 600.0 { bold = true; }+ } else if let Some(name) = desc.get(b"FontWeight").ok().and_then(|o| o.as_name().ok()) {+ if String::from_utf8_lossy(name).to_lowercase().contains("bold") { bold = true; }+ }+ if let Some(stemv) = desc.get(b"StemV").ok().and_then(num) {+ if stemv.abs() > 140.0 { bold = true; }+ }+ if desc.get(b"FontName").ok().and_then(|o| o.as_name().ok())+ .map(|n| String::from_utf8_lossy(n).to_lowercase().contains("bold")).unwrap_or(false) { bold = true; }+ }+ FontInfo { two_byte, to_unicode,@@ -162,6 +241,8 @@ pub(crate) fn font_info(doc: &Document, font: &lopdf::Dictionary) -> FontInfo { widths, default_width, t3,+ style: FontStyle { bold, italic },+ base_font: base_font_name, } }
pdf/src/main/rust/src/model.rs
diff --git a/pdf/src/main/rust/src/model.rs b/pdf/src/main/rust/src/model.rsindex 8fa2f29a7f..99ff3a9660 100644--- a/pdf/src/main/rust/src/model.rs+++ b/pdf/src/main/rust/src/model.rs@@ -2,6 +2,7 @@ use crate::*; /// Drawing primitives in PDF page space (origin bottom-left). Kotlin performs /// the Y-flip and fit-to-width scale. Extended v3 adds GroupPush/Pop and blend.+/// v8 adds font style flags for bold/italic synthesis. pub(crate) enum Prim { Text { x: f32,@@ -18,6 +19,12 @@ pub(crate) enum Prim { render_mode: u8, /// Blend mode (from the graphics-state `/BM`). Serialized in v5. blend: BlendMode,+ /// Font style flags recovered from BaseFont / FontDescriptor (v8).+ is_bold: bool,+ is_italic: bool,+ /// PDF text rise (Ts) and horizontal scale (Tz fraction) for verif; used for+ /// spacing / synthetic slant debugging (not strictly needed on wire but helps).+ h_scale: f32, }, Fill { argb: u32,
pdf/src/main/rust/src/tests.rs
diff --git a/pdf/src/main/rust/src/tests.rs b/pdf/src/main/rust/src/tests.rsindex 8f6020f762..1c9cd7d73e 100644--- a/pdf/src/main/rust/src/tests.rs+++ b/pdf/src/main/rust/src/tests.rs@@ -187,6 +187,8 @@ use crate::*; widths: HashMap::from([(0x41, 0.5), (0x42, 0.5)]), default_width: 0.5, t3: None,+ style: FontStyle::default(),+ base_font: String::new(), }; let mut fonts = HashMap::new(); fonts.insert(b"F1".to_vec(), fi);@@ -229,6 +231,8 @@ use crate::*; widths: HashMap::new(), default_width: 0.5, t3: None,+ style: FontStyle::default(),+ base_font: String::new(), }; let mut fonts = HashMap::new(); fonts.insert(b"F1".to_vec(), fi);
pdf/src/main/rust/src/wire.rs
diff --git a/pdf/src/main/rust/src/wire.rs b/pdf/src/main/rust/src/wire.rsindex 0823e0f28b..4e689b9e0b 100644--- a/pdf/src/main/rust/src/wire.rs+++ b/pdf/src/main/rust/src/wire.rs@@ -1,9 +1,11 @@ use crate::*; const WIRE_MAGIC: u32 = 0x50444657; // 'PDFW'- const WIRE_VERSION: u32 = 7;+ const WIRE_VERSION: u32 = 8; #[allow(dead_code)] const WIRE_VERSION_V2: u32 = 2;+ const WIRE_VERSION_V7: u32 = 7;+ const WIRE_VERSION_V8: u32 = 8; const TAG_TEXT: u8 = 1; const TAG_FILL: u8 = 2; const TAG_STROKE: u8 = 3;@@ -22,12 +24,12 @@ use crate::*; const PATHOP_CUBIC: u8 = 2; const PATHOP_CLOSE: u8 = 3; - /// Serialize a page into a compact little-endian buffer v6:+ /// Serialize a page into a compact little-endian buffer v8: /// /// ```text- /// header: u32 MAGIC=0x50444657, u32 VERSION=6, f32 pageWidth, f32 pageHeight, u32 primitiveCount+ /// header: u32 MAGIC=0x50444657, u32 VERSION=8, f32 pageWidth, f32 pageHeight, u32 primitiveCount /// per primitive: u8 tag, then payload- /// 1 Text: f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5), f32 advance (v7)+ /// 1 Text: f32 x, f32 y, f32 size, u32 argb, u16 len, [utf8], u8 hasStroke, u32 strokeArgb, f32 strokeWidth, u8 renderMode (v4), u8 blend (v5), f32 advance (v7), u8 fontFlags (v8: bit0 bold bit1 italic), f32 hScale (v8) /// 2 Fill: u32 argb, u8 evenOdd, u16 nContours, [u16 nPts, [f32 x,y]...]... (v6), u8 blend (v5) /// 3 Stroke: u32 argb, f32 width, u8 nDash, [f32 dash]..., f32 phase, u8 cap, u8 join, f32 miter, u16 nPts, [f32 x, f32 y]..., u8 blend (v5) /// 4 Image: 6×f32 ctm, u32 w, u32 h, u8 format, u32 len, [bytes] (format 0=RGBA8888, 1=JPEG)@@ -40,7 +42,7 @@ use crate::*; /// 10 SoftMaskPush: u8 maskType (0 alpha, 1 luminosity) (v5) /// 11 SoftMaskContent: empty (v5) /// 12 SoftMaskPop: empty (v5)- /// v1 legacy (no magic), v2/v3/v4 remain backward compatible for cached pages.+ /// v1 legacy (no magic), v2..v7 remain backward compatible for cached pages. /// ``` pub fn serialize(page: &PageData) -> Vec<u8> { let mut buf = Vec::new();@@ -51,7 +53,7 @@ use crate::*; buf.extend_from_slice(&(page.prims.len() as u32).to_le_bytes()); for prim in &page.prims { match prim {- Prim::Text { x, y, size, argb, text, stroke_argb, stroke_width, advance, render_mode, blend } => {+ Prim::Text { x, y, size, argb, text, stroke_argb, stroke_width, advance, render_mode, blend, is_bold, is_italic, h_scale } => { buf.push(TAG_TEXT); buf.extend_from_slice(&x.to_le_bytes()); buf.extend_from_slice(&y.to_le_bytes());@@ -73,6 +75,11 @@ use crate::*; buf.push(*render_mode); // v4 buf.push(*blend as u8); // v5 buf.extend_from_slice(&advance.to_le_bytes()); // v7: device-space glyph advance+ let mut font_flags = 0u8;+ if *is_bold { font_flags |= 1; }+ if *is_italic { font_flags |= 2; }+ buf.push(font_flags); // v8: bold/italic+ buf.extend_from_slice(&h_scale.to_le_bytes()); // v8 } Prim::Fill { argb, even_odd, contours, blend } => { buf.push(TAG_FILL);@@ -244,6 +251,9 @@ use crate::*; advance: 12.0, render_mode: 0, blend: BlendMode::Multiply,+ is_bold: true,+ is_italic: false,+ h_scale: 1.0, }, Prim::Fill { argb: 0xFFAABBCC,@@ -304,6 +314,8 @@ use crate::*; assert_eq!(r.u8(), 0); // render_mode (v4) assert_eq!(r.u8(), BlendMode::Multiply as u8); // blend (v5) assert!((r.f32() - 12.0).abs() < 1e-6); // advance (v7)+ assert_eq!(r.u8(), 1); // fontFlags bold (v8)+ assert!((r.f32() - 1.0).abs() < 1e-6); // h_scale (v8) assert_eq!(r.u8(), TAG_FILL); assert_eq!(r.u32(), 0xFFAABBCC);