Android PDF Writer 在 WRAP_CONTENT 时忽略我的 View 高度

标签 android

我正在尝试使用 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 上包装内容

enter image description here

在 Textview 上 300dp

enter image description here

最佳答案

这里的问题是 TextViewdraw() 之前没有机会重新布局并调整大小以适应新文本调用在设置该文本后发生。

虽然我们发现在抽奖之前加入轻微的延迟会奏效,但这有点老套,因为我们实际上只是在猜测一个合适的时间间隔。

相反,我们可以通过移动 draw() 将绘制和后续操作排入队列,使其在布局之后立即发生。然后调用 Runnable , 并调用 post()TextView 上在设置文本后使用它。

关于Android PDF Writer 在 WRAP_CONTENT 时忽略我的 View 高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50477244/

相关文章:

android - Android 智能手机和其他设备之间的直接 Wifi 通信

Android:在没有 BluetoothManagerCallback 的情况下调用了 getBluetoothService()

java - 如何轻松提交Android Studio

android - 下载 PDF 文件

android - 可以在 Android 中使用空布局吗?

安卓 : How to create a customizable time table like structure with scrolling

Android 渐变颜色 - 不正确的结果

android - Flutter Dart 在构建期间使用过多内存

Android:如何创建一个实现 Parcelable 的类,其中包含一个非静态自定义类的 ArrayList

android - 连接打印机的api