我正在尝试使用 Android 内置的 PDF 编写器,但它忽略了我使用换行内容的 View 的高度,并在宽度和高度上截断了文本。
不过,当我添加固定高度(300dp)时,它可以显示全部内容。
在我的例子中,内容都是动态的,非常基本的 html,我不能在我的布局上使用固定高度。我也不想将它加载到 webview 中,因为它将是简单的 html。
我试过编写 rootview 和 textview,两者的行为相同。
有没有办法做到这一点并使用包装内容?
我附上了两者的图片。
fun printDocument() {
var printAttributes =
PrintAttributes.Builder().setColorMode(PrintAttributes.COLOR_MODE_COLOR)
.setMediaSize(PrintAttributes.MediaSize.NA_LETTER)
.setResolution(Resolution("zooey", Context.PRINT_SERVICE, 2000, 2000))
.setMinMargins(Margins(25, 25, 25, 25)).build()
var document = PrintedPdfDocument(this, printAttributes)
var page = document.startPage(0)
val textView = findViewById<TextView>(R.id.textView)
textView.text =
"this is a silly problem\nand really annoying\nvery annoying"
textView.draw(page.canvas);
document.finishPage(page);
val file = File(filesDir, "myPdf.pdf")
val outputStream = file.outputStream()
document.writeTo(outputStream)
document.close()
outputStream.close()
}
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootview"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Print" />
</LinearLayout>
在 TextView 上包装内容
在 Textview 上 300dp
最佳答案
这里的问题是 TextView
在 draw()
之前没有机会重新布局并调整大小以适应新文本调用在设置该文本后发生。
虽然我们发现在抽奖之前加入轻微的延迟会奏效,但这有点老套,因为我们实际上只是在猜测一个合适的时间间隔。
相反,我们可以通过移动 draw()
将绘制和后续操作排入队列,使其在布局之后立即发生。然后调用 Runnable
, 并调用 post()
在 TextView
上在设置文本后使用它。
关于Android PDF Writer 在 WRAP_CONTENT 时忽略我的 View 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50477244/