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.

Word PDF from the editor's own pages, calmer search unfurl, back waits 280 ms

chethan6164ebd3dcf77ec
diff --git a/DESIGN.md b/DESIGN.md
index 12d772b..d9d40c5 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -126,7 +126,7 @@ by hand must do the same. `settle`, `fade` and layout springs never bounce and i
Back.
- Long-press on a glass button blooms (grows ≤ ~14 dp, glows brighter, one LongPress haptic). A
long-press **action** runs on release, never mid-press.
-- A tapped back button (`GlassBackButton`) leaves after `GlassMotion.BackTapDelayMillis` (140 ms),
+- A tapped back button (`GlassBackButton`) leaves after `GlassMotion.BackTapDelayMillis` (280 ms),
so the press is seen first, as on iOS. Not longer: it must never read as lag. The system back
gesture stays instant, and Reduce glass motion skips the wait.
@@ -200,6 +200,10 @@ by hand must do the same. `settle`, `fade` and layout springs never bounce and i
20 dp icons, the Word editor's size, in the PDF and PowerPoint viewers too. The morph grows to
twice its size while armed. Settings -> Personalization -> Swap share and open makes the tap
share and the hold-and-swipe open; the ink still follows what is behind it.
+- The Word editor's PDF and Print buttons make the PDF from the editor's own pages
+ (`DocxPdfWriter`: same styles, labels, pictures, tables and Word's page breaks, real text), or
+ from the Office engine when it is installed. Never the old web-preview converter, whose output
+ looks like the previous viewer.
- Word documents open as pages, desktop-like: true proportions and margins, fit to width, pinch to
zoom (the page relays out sharp, it is never bitmap-scaled), Word's own page breaks.
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassMotion.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassMotion.kt
index 0f1c835..716c9ac 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassMotion.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassMotion.kt
@@ -68,5 +68,5 @@ object GlassMotion {
* How long a tapped back button waits before leaving: long enough for the swell to land and start
* springing back (the press is visible, as on iOS), short enough that it never reads as lag.
*/
- const val BackTapDelayMillis = 140L
+ const val BackTapDelayMillis = 280L
}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassSearchHeader.kt b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassSearchHeader.kt
index b1abc9c..2d1bc99 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassSearchHeader.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/components/GlassSearchHeader.kt
@@ -1,5 +1,6 @@
package com.chethan616.clearpdf.ui.components
+import kotlinx.coroutines.flow.first
import androidx.activity.compose.BackHandler
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloat
@@ -99,7 +100,8 @@ val GlassSearchPillHeight = 36.dp
* what each one is allowed to do: `progress` owns the layout width and stays critically damped (an
* overshooting width re-measures the glass and re-runs its blur+lens at a new size, and a negative
* one throws), `fade` owns alpha and stays critically damped (overshoot clips at 1.0 and reads as a
- * flicker), and `bounce` owns the scales and the icon spin, where overshoot is the whole point.
+ * flicker), and `grow` owns the scales and the icon spin. `grow` is critically damped too; the
+ * spring you feel is a separate wobble with the glass buttons' physics (see below).
*/
@Composable
fun GlassSearchHeader(
@@ -129,20 +131,32 @@ fun GlassSearchHeader(
transitionSpec = { GlassMotion.fade() },
label = "searchFade"
) { if (it) 1f else 0f }
- // The bounce rides its own clock so it can overshoot without dragging `progress` — and therefore
- // the layout width — past 1. Everything it drives is a draw-time property, so the overshoot costs
- // a layer-matrix update, not a re-measure: `drawBackdrop` never re-runs its blur or lens.
- // Symmetric on purpose: this used to spring open with `morph()` but close with the fully
- // rigid `settle()` (no overshoot at all), on the theory that overshooting past the field's
- // floor scale on the way in would look broken. It doesn't — every use of `bounce` below either
- // clamps to [0,1] (the pill's shrink) or tolerates a few percent past its floor for a couple of
- // frames (the field's grow-in, the icon's spin) — so there was nothing actually protecting
- // against, just an animation that sprang open and then went dead on the way back, closing every
- // single time compared with opening.
- val bounce by transition.animateFloat(
- transitionSpec = { GlassMotion.morph() },
- label = "searchBounce"
+ // The unfurl itself never overshoots. It used to ride `morph()`, and a 0.32 -> 1 scale on a
+ // full-width capsule turns that spring's overshoot into tens of dp (far more under Bouncy /
+ // Super springy), with the icon swinging well past its quarter turn: the pill over-jiggled.
+ // Now it lands cleanly at the morph's speed, and the spring comes from `wobble` below.
+ val growState = transition.animateFloat(
+ transitionSpec = { spring(dampingRatio = 1f, stiffness = MotionSettings.stiffness(420f)) },
+ label = "searchGrow"
) { if (it) 1f else 0f }
+ val grow by growState
+ // The glass buttons' release jiggle (InteractiveHighlight): once the capsule lands it is kicked
+ // into one out-of-phase squash, about 2.5 dp a side, on the same spring and Motion settings as
+ // every LiquidButton, instead of the whole pill rebounding.
+ val wobble = remember { androidx.compose.animation.core.Animatable(0f, 0.001f) }
+ val firstRun = remember { booleanArrayOf(true) }
+ LaunchedEffect(active) {
+ if (firstRun[0]) { firstRun[0] = false; return@LaunchedEffect }
+ val target = if (active) 1f else 0f
+ androidx.compose.runtime.snapshotFlow { growState.value }
+ .first { kotlin.math.abs(it - target) < 0.15f }
+ wobble.snapTo(0f)
+ wobble.animateTo(
+ 0f,
+ GlassMotion.wobble(),
+ initialVelocity = 34f * MotionSettings.style.wobble.coerceIn(0f, 3f)
+ )
+ }
val dismiss = {
onQueryChange("")
@@ -184,11 +198,12 @@ fun GlassSearchHeader(
Box(
Modifier.graphicsLayer {
alpha = 1f - fade
- // Clamped: the pill only needs the eased shape, not the overshoot — it is on
- // its way out and a rebound would fight the fade.
- val s = lerp(1f, 0.86f, bounce.coerceIn(0f, 1f))
- scaleX = s
- scaleY = s
+ // Shrinks toward the circle as search opens; coming back it gets the
+ // buttons' landing jiggle.
+ val s = lerp(1f, 0.86f, grow)
+ val w = if (active) 0f else wobble.value
+ scaleX = s + w * (2.5f.dp.toPx() / size.width).coerceAtMost(0.045f)
+ scaleY = s - w * (2.5f.dp.toPx() / size.height).coerceAtMost(0.045f)
}
) {
GlassTitlePill(
@@ -206,11 +221,12 @@ fun GlassSearchHeader(
.graphicsLayer {
alpha = fade
// Grow out of the circle: the capsule's right edge is pinned, so it
- // unfurls leftward, overshoots past full width and springs back. The
- // overshoot runs into the leading slot, which has collapsed by then.
+ // unfurls leftward and lands, then jiggles like a released glass button
+ // (X and Y out of phase, ~2.5 dp).
transformOrigin = TransformOrigin(1f, 0.5f)
- scaleX = lerp(0.32f, 1f, bounce)
- scaleY = lerp(0.72f, 1f, bounce)
+ val w = if (active) wobble.value else 0f
+ scaleX = lerp(0.32f, 1f, grow) + w * (2.5f.dp.toPx() / size.width).coerceAtMost(0.045f)
+ scaleY = lerp(0.72f, 1f, grow) - w * (2.5f.dp.toPx() / size.height).coerceAtMost(0.045f)
}
) {
GlassSearchPill(
@@ -239,10 +255,10 @@ fun GlassSearchHeader(
) {
val tint = LiquidGlassColors.text(LocalIsDarkMode.current)
// The icon spins a quarter turn as it swaps, so the circle feels like it re-purposes
- // rather than just blinking to a new glyph. On `bounce`, so it overshoots the turn in
- // step with the capsule instead of arriving ahead of it.
+ // rather than just blinking to a new glyph. It lands with the capsule and shares its
+ // small wobble rather than swinging past the turn on its own.
Box(
- Modifier.graphicsLayer { rotationZ = lerp(0f, 90f, bounce) },
+ Modifier.graphicsLayer { rotationZ = lerp(0f, 90f, grow) + wobble.value * 6f },
contentAlignment = Alignment.Center
) {
if (showTitle) {
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxEditorScreen.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxEditorScreen.kt
index 859fefa..a6b0684 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxEditorScreen.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxEditorScreen.kt
@@ -234,7 +234,7 @@ private enum class DocPanel { NONE, TEXT_COLOR, HIGHLIGHT }
/** Formatting chosen with nothing selected: it applies to what is typed next at [at]. */
private class Pending(val paraId: Long, val at: Int, val fmt: CharFmt)
-private sealed class DocItem(val key: Any, val page: Int) {
+internal sealed class DocItem(val key: Any, val page: Int) {
/** A paragraph, or (reading) the part of one that falls on [page], when Word broke it across pages. */
class Para(
val para: DocPara,
@@ -254,7 +254,7 @@ private sealed class DocItem(val key: Any, val page: Int) {
class Bottom(page: Int) : DocItem("bottom", page)
}
-private class Flat(val items: List<DocItem>, val indexOf: Map<Long, Int>, val pageStarts: List<Int>) {
+internal class Flat(val items: List<DocItem>, val indexOf: Map<Long, Int>, val pageStarts: List<Int>) {
val pages: Int get() = pageStarts.size
}
@@ -264,7 +264,7 @@ private class Flat(val items: List<DocItem>, val indexOf: Map<Long, Int>, val pa
* breaks, and before paragraphs set to start a page. While reading, a paragraph Word broke across
* two pages is shown in two parts; while editing it stays whole (one field) and the page ends after it.
*/
-private fun flatten(blocks: List<DocBlock>, styles: DocxStyles, splitParas: Boolean): Flat {
+internal fun flatten(blocks: List<DocBlock>, styles: DocxStyles, splitParas: Boolean): Flat {
val items = ArrayList<DocItem>()
val index = HashMap<Long, Int>()
val pageStarts = arrayListOf(0)
@@ -757,8 +757,10 @@ private fun DocxEditorContent(
// The exact page layout comes from the PDF path, which uses the Office engine (LibreOffice)
// whenever it is installed.
fun openAsPdf() {
- if (!viewModel.dirty) meta.sourceUri?.let(onOpenPdf)
- else viewModel.exportToPdf(context) { pdf ->
+ // Always this document's own pages as a PDF (see exportToPdf). Handing the untouched .docx
+ // to the PDF route made that route convert it with the old web preview instead, which
+ // opened the previous viewer's look rather than the page being read.
+ viewModel.exportToPdf(context) { pdf ->
if (pdf != null) onOpenPdf(pdf) else Toast.makeText(context, R.string.docx_read_failed, Toast.LENGTH_SHORT).show()
}
}
@@ -1496,9 +1498,9 @@ private fun StaticBlock(block: DocBlock, look: DocxLook, env: DocEnv) {
// ── pictures ──────────────────────────────────────────────────────────────────
-private class DecodedPicture(val image: ImageBitmap, val paperLike: Boolean)
+internal class DecodedPicture(val image: ImageBitmap, val paperLike: Boolean)
-private object DocImages {
+internal object DocImages {
private val cache = object : LruCache<String, Pair<Bitmap, Boolean>>(48 * 1024 * 1024) {
override fun sizeOf(key: String, value: Pair<Bitmap, Boolean>) = value.first.byteCount
}
@@ -1579,7 +1581,7 @@ private fun DocPicture(info: ObjInfo, pkg: DocxPackage, look: DocxLook, maxWidth
// ── tables ────────────────────────────────────────────────────────────────────
-private class TableLook(
+internal class TableLook(
val fractions: FloatArray,
val width: Dp,
val indent: Dp,
@@ -1593,12 +1595,12 @@ private class TableLook(
val scale: Float
)
-private class CellProps(val span: Int, val vContinue: Boolean, val fill: Int?, val vAlign: String?)
+internal class CellProps(val span: Int, val vContinue: Boolean, val fill: Int?, val vAlign: String?)
private val cellPropsCache = HashMap<String, CellProps>()
private val tableLookCache = java.util.WeakHashMap<DocTable, Pair<Float, TableLook>>()
-private fun cellProps(tcPr: String): CellProps = synchronized(cellPropsCache) {
+internal fun cellProps(tcPr: String): CellProps = synchronized(cellPropsCache) {
cellPropsCache.getOrPut(tcPr) {
val root = if (tcPr.isEmpty()) null else XmlScan.scan(tcPr).children.firstOrNull()
fun child(n: String): XNode? = root?.child(n)
@@ -1616,7 +1618,7 @@ private fun cellProps(tcPr: String): CellProps = synchronized(cellPropsCache) {
* A table at its real size on the page: Word's column grid, alignment and indent. Only a table
* wider than the page's text area (plus a little of the margin, which Word allows) is shrunk.
*/
-private fun tableLookOf(t: DocTable, pkg: DocxPackage, look: DocxLook, availWidth: Dp): TableLook {
+internal fun tableLookOf(t: DocTable, pkg: DocxPackage, look: DocxLook, availWidth: Dp): TableLook {
val cacheKey = look.scale * 100_000f + availWidth.value
synchronized(tableLookCache) { tableLookCache[t]?.let { if (it.first == cacheKey) return it.second } }
val tblPr = if (t.tblPr.isEmpty()) null else XmlScan.scan(t.tblPr).children.firstOrNull()
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxPdfWriter.kt b/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxPdfWriter.kt
new file mode 100644
index 0000000..3458fe5
--- /dev/null
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/screen/DocxPdfWriter.kt
@@ -0,0 +1,358 @@
+package com.chethan616.clearpdf.ui.screen
+
+import android.content.Context
+import android.graphics.Paint
+import android.graphics.RectF
+import android.graphics.pdf.PdfDocument
+import android.util.Log
+import androidx.compose.ui.geometry.CornerRadius
+import androidx.compose.ui.geometry.Offset
+import androidx.compose.ui.geometry.Size
+import androidx.compose.ui.graphics.Canvas
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.asAndroidBitmap
+import androidx.compose.ui.graphics.drawscope.CanvasDrawScope
+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.drawscope.translate
+import androidx.compose.ui.graphics.nativeCanvas
+import androidx.compose.ui.text.AnnotatedString
+import androidx.compose.ui.text.TextMeasurer
+import androidx.compose.ui.text.drawText
+import androidx.compose.ui.text.font.createFontFamilyResolver
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.Constraints
+import androidx.compose.ui.unit.Density
+import androidx.compose.ui.unit.LayoutDirection
+import androidx.compose.ui.unit.dp
+import com.chethan616.clearpdf.docx.DocBlock
+import com.chethan616.clearpdf.docx.DocPara
+import com.chethan616.clearpdf.docx.DocRaw
+import com.chethan616.clearpdf.docx.DocRow
+import com.chethan616.clearpdf.docx.DocTable
+import com.chethan616.clearpdf.docx.DocxObjects
+import com.chethan616.clearpdf.docx.DocxPackage
+import com.chethan616.clearpdf.docx.ObjInfo
+import com.chethan616.clearpdf.docx.RProps
+import com.chethan616.clearpdf.docx.XmlScan
+import java.io.File
+import java.io.FileOutputStream
+import kotlin.math.roundToInt
+
+/**
+ * A Word document as a PDF, drawn from the Word editor's own page layout: the same [DocxLook]
+ * styles, list labels, pictures, tables and Word's page breaks ([flatten]) the editor shows, laid
+ * out with Compose's text engine at one unit per point and drawn straight onto [PdfDocument] pages,
+ * so the text stays real, selectable text.
+ *
+ * This replaced the old web-preview conversion for the editor's PDF and Print buttons, which
+ * produced the previous viewer's look rather than the page the person was reading. Where our fonts
+ * run longer than Word's and a page overflows, the content carries on to a new page, breaking
+ * between lines, pictures and table rows.
+ */
+internal object DocxPdfWriter {
+ fun write(context: Context, pkg: DocxPackage, blocks: List<DocBlock>, out: File): Boolean =
+ runCatching { Exporter(context, pkg, blocks).run(out); true }
+ .onFailure { Log.w("DocxPdf", "Couldn't draw the document as a PDF", it) }
+ .getOrDefault(false)
+}
+
+/** Something laid out: its height in points, where a page may end inside it, and how to draw it at (0, 0). */
+private class Laid(val height: Float, val breaks: FloatArray, val draw: DrawScope.() -> Unit)
+
+private class Exporter(context: Context, private val pkg: DocxPackage, private val blocks: List<DocBlock>) {
+ private val density = Density(1f, 1f)
+ private val look = DocxLook(pkg, false, 1f, 1f, DocxLook.carlito())
+ private val measurer = TextMeasurer(createFontFamilyResolver(context), density, LayoutDirection.Ltr, 0)
+ private val labels = numberingLabels(pkg, blocks)
+ private val setup = pkg.page
+ private val pageW = (setup.width / 20f).coerceAtLeast(72f)
+ private val pageH = (setup.height / 20f).coerceAtLeast(72f)
+ private val left = setup.left.coerceAtLeast(0) / 20f
+ private val right = setup.right.coerceAtLeast(0) / 20f
+ private val top = setup.top.coerceAtLeast(0) / 20f
+ private val bottom = setup.bottom.coerceAtLeast(0) / 20f
+ private val textW = (pageW - left - right).coerceAtLeast(72f)
+ private val scope = CanvasDrawScope()
+ private val bitmapPaint = Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG)
+
+ fun run(out: File) {
+ val flat = flatten(blocks, pkg.styles, splitParas = true)
+ val doc = PdfDocument()
+ var page: PdfDocument.Page? = null
+ var number = 0
+ var y = 0f
+ var fresh = true
+ val limit = pageH - bottom
+
+ fun newPage() {
+ page?.let(doc::finishPage)
+ number++
+ page = doc.startPage(PdfDocument.PageInfo.Builder(pageW.roundToInt(), pageH.roundToInt(), number).create())
+ y = top
+ fresh = true
+ }
+
+ fun slice(l: Laid, from: Float, to: Float) {
+ val p = page ?: return
+ val at = y
+ scope.draw(density, LayoutDirection.Ltr, Canvas(p.canvas), Size(pageW, pageH)) {
+ clipRect(0f, at, pageW, at + (to - from)) {
+ translate(left, at - from) { l.draw(this) }
+ }
+ }
+ y += to - from
+ fresh = false
+ }
+
+ // Whole when it fits; otherwise up to the last line (or picture, or row) that does, and the
+ // rest on the next page. Something taller than a whole page is cut where the page ends.
+ fun place(l: Laid) {
+ var from = 0f
+ while (l.height - from > 0.01f) {
+ val avail = limit - y
+ if (l.height - from <= avail + 0.5f) { slice(l, from, l.height); return }
+ var cut = -1f
+ for (b in l.breaks) if (b > from + 0.5f && b - from <= avail && b > cut) cut = b
+ when {
+ cut > 0f -> { slice(l, from, cut); from = cut; newPage() }
+ !fresh -> newPage()
+ else -> {
+ val to = from + avail.coerceAtLeast(1f)
+ slice(l, from, to); from = to; newPage()
+ }
+ }
+ }
+ }
+
+ for (item in flat.items) when (item) {
+ is DocItem.Top -> newPage()
+ // Word's own page break; skipped when an overflow has just started a page anyway.
+ is DocItem.Gap -> if (!fresh) newPage()
+ is DocItem.Bottom -> Unit
+ is DocItem.Para -> place(
+ para(item.para, look, textW, null, item.range, item.spaceTop && item.first, item.spaceBottom && item.last)
+ )
+ is DocItem.TRow -> place(row(item.table, item.row, item.rowIndex, look, textW))
+ }
+ if (page == null) newPage()
+ page?.let(doc::finishPage)
+ out.parentFile?.mkdirs()
+ try {
+ FileOutputStream(out).use { doc.writeTo(it) }
+ } finally {
+ doc.close()
+ }
+ }
+
+ /** One paragraph, as [ParagraphBlock] lays it out: pictures, text boxes, label + text, rule. */
+ private fun para(
+ p: DocPara,
+ lk: DocxLook,
+ width: Float,
+ cell: RProps?,
+ range: IntRange?,
+ spaceTop: Boolean,
+ spaceBottom: Boolean
+ ): Laid {
+ val pl = lk.para(p, cell)
+ val full = lk.annotate(p, pl, cell)
+ val annotated = if (range == null) full else full.subSequence(range.first, (range.last + 1).coerceAtMost(full.length))
+ val objects = p.fmts.withIndex()
+ .filter { (i, f) -> f.obj != null && (range == null || i in range) }
+ .map { DocxObjects.info(it.value.obj!!) }
+ val pictures = objects.filter { it.imageRid != null }
+ val boxes = objects.filter { it.textBox.isNotEmpty() }
+ val blank = annotated.text.all { it == '​' || it.isWhitespace() }
+ val first = range == null || range.first == 0
+ val label = if (first) labels[p.id] else null
+ val rtl = pl.rtl
+ val dir = if (rtl) LayoutDirection.Rtl else LayoutDirection.Ltr
+ val padStart = pl.padStart.value
+ val padEnd = pl.padEnd.value
+ val contentW = (width - padStart - padEnd).coerceAtLeast(8f)
+ val contentX = if (rtl) padEnd else padStart
+ val before = if (spaceTop) pl.before.value else 0f
+ val after = if (spaceBottom) pl.after.value else 0f
+
+ class Part(val x: Float, val y: Float, val l: Laid)
+ val parts = ArrayList<Part>()
+ val breaks = ArrayList<Float>()
+ var y = before
+
+ for (pic in pictures) {
+ val l = picture(pic, lk, contentW, pl.style.textAlign, rtl) ?: continue
+ parts += Part(contentX, y, l); y += l.height; breaks += y
+ }
+ for (box in boxes) {
+ val inner = stack(box.textBox, lk, (contentW - 16f).coerceAtLeast(8f))
+ val h = inner.height + 16f
+ val ink = lk.ink.copy(0.22f)
+ val l = Laid(h + 8f, floatArrayOf()) {
+ drawRoundRect(ink, Offset(0f, 4f), Size(contentW, h), CornerRadius(4f), style = Stroke(0.5f))
+ translate(8f, 12f) { inner.draw(this) }
+ }
+ parts += Part(contentX, y, l); y += l.height; breaks += y
+ }
+ if (!(blank && (pictures.isNotEmpty() || boxes.isNotEmpty()))) {
+ val labelW = if (label != null) pl.hanging.value else 0f
+ val bodyW = (contentW - labelW).coerceAtLeast(8f)
+ val text = measurer.measure(
+ annotated,
+ if (first) pl.style else pl.style.copy(textIndent = null),
+ constraints = Constraints.fixedWidth(bodyW.roundToInt().coerceAtLeast(1)),
+ layoutDirection = dir
+ )
+ val lab = if (label != null && labelW >= 1f) measurer.measure(
+ AnnotatedString(label),
+ pl.style.copy(textAlign = TextAlign.Start, textIndent = null),
+ overflow = TextOverflow.Clip,
+ maxLines = 1,
+ constraints = Constraints.fixedWidth(labelW.roundToInt().coerceAtLeast(1)),
+ layoutDirection = dir
+ ) else null
+ // Label and text share their first baseline, like the editor's alignByBaseline row.
+ val base = maxOf(text.firstBaseline, lab?.firstBaseline ?: 0f)
+ val ty = base - text.firstBaseline
+ val ly = base - (lab?.firstBaseline ?: 0f)
+ val rowH = maxOf(ty + text.size.height, if (lab != null) ly + lab.size.height else 0f)
+ val textX = if (rtl) contentX else contentX + labelW
+ val labelX = if (rtl) contentX + bodyW else contentX
+ val rowY = y
+ for (i in 0 until text.lineCount) breaks += rowY + ty + text.getLineBottom(i)
+ parts += Part(0f, y, Laid(rowH, floatArrayOf()) {
+ drawText(text, topLeft = Offset(textX, ty))
+ lab?.let { drawText(it, topLeft = Offset(labelX, ly)) }
+ })
+ y += rowH
+ }
+ if (pl.borderBottom && (range == null || range.last >= p.text.length - 1)) {
+ val ink = lk.ink.copy(0.55f)
+ parts += Part(contentX, y, Laid(4f, floatArrayOf()) {
+ drawLine(ink, Offset(0f, 3.5f), Offset(contentW, 3.5f), 1f)
+ })
+ y += 4f
+ }
+ val contentBottom = y
+ y += after
+ val shading = pl.shading
+ return Laid(y, breaks.toFloatArray()) {
+ if (shading != null && contentBottom > before) {
+ drawRect(shading, Offset(0f, before), Size(width, contentBottom - before))
+ }
+ for (part in parts) translate(part.x, part.y) { part.l.draw(this) }
+ }
+ }
+
+ /** A picture at its size in the document, aligned like [DocPicture], with 2 pt above and below. */
+ private fun picture(info: ObjInfo, lk: DocxLook, maxWidth: Float, paraAlign: TextAlign?, rtl: Boolean): Laid? {
+ val rid = info.imageRid ?: return null
+ val bytes = pkg.image(rid) ?: return null
+ val want = if (info.widthPt > 0f) info.widthPt * lk.scale else maxWidth
+ val w = want.coerceAtMost(maxWidth.coerceAtLeast(24f)).coerceAtLeast(12f)
+ // About 150 dpi: sharp in print without a camera photo's full weight.
+ val target = (w * 2.1f).roundToInt().coerceIn(64, 1800)
+ val pic = DocImages.decode("$rid@${System.identityHashCode(pkg)}@pdf$target", bytes, target)
+ val ratio = if (info.widthPt > 0f && info.heightPt > 0f) info.heightPt / info.widthPt
+ else pic?.image?.let { it.height.toFloat() / it.width.coerceAtLeast(1) } ?: 0.6f
+ val h = w * ratio.coerceIn(0.05f, 20f)
+ val start = when (info.hAlign) {
+ "center" -> 0.5f
+ "right", "outside" -> 1f
+ "left", "inside" -> 0f
+ else -> when (paraAlign) {
+ TextAlign.Center -> 0.5f
+ TextAlign.End, TextAlign.Right -> 1f
+ else -> 0f
+ }
+ }
+ val x = (maxWidth - w) * (if (rtl) 1f - start else start)
+ val bmp = pic?.image?.asAndroidBitmap()
+ return Laid(h + 4f, floatArrayOf()) {
+ if (bmp != null) drawIntoCanvas { it.nativeCanvas.drawBitmap(bmp, null, RectF(x, 2f, x + w, 2f + h), bitmapPaint) }
+ }
+ }
+
+ /** Blocks one under another (table cells, text boxes, content controls). */
+ private fun stack(list: List<DocBlock>, lk: DocxLook, width: Float, cell: RProps? = null): Laid {
+ val parts = ArrayList<Pair<Float, Laid>>()
+ val breaks = ArrayList<Float>()
+ var y = 0f
+ fun add(l: Laid) {
+ parts += y to l
+ for (b in l.breaks) breaks += y + b
+ y += l.height
+ breaks += y
+ }
+ for (b in list) when (b) {
+ is DocPara -> add(para(b, lk, width, cell, null, spaceTop = true, spaceBottom = true))
+ is DocTable -> for ((i, r) in b.rows.withIndex()) add(row(b, r, i, lk, width))
+ is DocRaw -> if (b.preview.isNotEmpty()) add(stack(b.preview, lk, width, cell))
+ }
+ return Laid(y, breaks.toFloatArray()) { for ((py, l) in parts) translate(0f, py) { l.draw(this) } }
+ }
+
+ /** One table row, as [TableRowBlock] lays it out: Word's grid, fills, borders, cell alignment. */
+ private fun row(table: DocTable, row: DocRow, rowIndex: Int, lk: DocxLook, availWidth: Float): Laid {
+ val tl = tableLookOf(table, pkg, lk, availWidth.dp)
+ val cellLook = lk.scaled(tl.scale)
+ val lastRow = rowIndex == table.rows.lastIndex
+ val gridBefore = if (row.trPr.isEmpty()) 0
+ else XmlScan.scan(row.trPr).children.firstOrNull()?.child("gridBefore")?.attr(row.trPr, "val")?.toIntOrNull() ?: 0
+ val header = tl.firstRow && rowIndex == 0
+ val banded = tl.bands && tl.bandFill != null && !header && (rowIndex - if (tl.firstRow) 1 else 0) % 2 == 0
+ val line = lk.ink.copy(0.55f)
+ val tw = tl.width.value
+ fun frac(from: Int, span: Int): Float {
+ var f = 0f
+ for (i in from until (from + span).coerceAtMost(tl.fractions.size)) f += tl.fractions[i]
+ return f.coerceAtLeast(0.0001f)
+ }
+ val x0 = when (tl.jc) {
+ "center" -> (availWidth - tw) / 2f
+ "right", "end" -> availWidth - tw
+ else -> tl.indent.value
+ }
+ val padH = 5.4f * cellLook.scale
+
+ class Cell(val x: Float, val w: Float, val fill: Color?, val content: Laid?, val vAlign: String?, val vContinue: Boolean, val last: Boolean)
+ val cells = ArrayList<Cell>()
+ var col = gridBefore
+ var x = x0 + if (gridBefore > 0) tw * frac(0, gridBefore) else 0f
+ for ((ci, c) in row.cells.withIndex()) {
+ val cp = cellProps(c.tcPr)
+ val fill = cp.fill ?: if (header) tl.headerFill else if (banded) tl.bandFill else null
+ val cw = tw * frac(col, cp.span)
+ val content = if (cp.vContinue) null
+ else stack(c.blocks, cellLook, (cw - 2f * padH).coerceAtLeast(4f), if (header) tl.headerR else null)
+ cells += Cell(x, cw, lk.fillOf(fill), content, cp.vAlign, cp.vContinue, ci == row.cells.lastIndex)
+ x += cw
+ col += cp.span
+ }
+ val rowH = (cells.maxOfOrNull { (it.content?.height ?: 0f) + 2f } ?: 2f).coerceAtLeast(2f)
+ return Laid(rowH, floatArrayOf()) {
+ for (c in cells) {
+ c.fill?.let { drawRect(it, Offset(c.x, 0f), Size(c.w, rowH)) }
+ c.content?.let { content ->
+ val free = rowH - 2f - content.height
+ val dy = 1f + when (c.vAlign) {
+ "center" -> free / 2f
+ "bottom" -> free
+ else -> 0f
+ }
+ translate(c.x + padH, dy) { content.draw(this) }
+ }
+ if (tl.borders) {
+ val sw = 0.5f
+ if (!c.vContinue) drawLine(line, Offset(c.x, 0f), Offset(c.x + c.w, 0f), sw)
+ drawLine(line, Offset(c.x, 0f), Offset(c.x, rowH), sw)
+ if (c.last) drawLine(line, Offset(c.x + c.w, 0f), Offset(c.x + c.w, rowH), sw)
+ if (lastRow) drawLine(line, Offset(c.x, rowH), Offset(c.x + c.w, rowH), sw)
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/DocxEditorViewModel.kt b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/DocxEditorViewModel.kt
index dcf32dc..927129f 100644
--- a/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/DocxEditorViewModel.kt
+++ b/app/src/main/java/com/chethan616/clearpdf/ui/viewmodel/DocxEditorViewModel.kt
@@ -302,12 +302,30 @@ class DocxEditorViewModel : ViewModel() {
}
}
+ /**
+ * The document as a PDF, for the PDF button and Print, best source first: the Office engine
+ * (LibreOffice, Word's own layout rules) when it is installed; otherwise the editor's own pages
+ * drawn straight into a PDF ([DocxPdfWriter]), exactly as they read here, unsaved edits
+ * included; and only if that fails, the old web-preview converter.
+ */
fun exportToPdf(context: Context, onDone: (Uri?) -> Unit) {
+ val p = pkg
+ val d = doc
+ val name = meta.fileName.ifBlank { "Document.docx" }
currentFile(context) { src ->
- if (src == null) return@currentFile onDone(null)
viewModelScope.launch {
- val out = withContext(Dispatchers.IO) {
- runCatching { com.chethan616.clearpdf.utils.UniversalDocumentConverter.convertToPdf(context, src) }.getOrNull()
+ val out = withContext(Dispatchers.Default) {
+ if (src != null) {
+ runCatching { com.chethan616.clearpdf.office.OfficeEngine.tryConvert(context, src, name.lowercase()) }
+ .getOrNull()?.let { return@withContext Uri.fromFile(it) }
+ }
+ if (p != null && d != null) {
+ val dir = File(context.cacheDir, "converted_pdfs/${System.currentTimeMillis()}")
+ val pdf = File(dir, name.substringBeforeLast('.').ifBlank { "Document" }.replace('/', '_') + ".pdf")
+ if (com.chethan616.clearpdf.ui.screen.DocxPdfWriter.write(context, p, d.blocks, pdf)) return@withContext Uri.fromFile(pdf)
+ }
+ if (src == null) null
+ else runCatching { com.chethan616.clearpdf.utils.UniversalDocumentConverter.convertToPdf(context, src) }.getOrNull()
}
onDone(out)
}