Reputation: 3582
I'm trying to use Androids built in PDF writer, but it's ignoring the height of my views that use wrap content and truncating the text on width and height.
When I add a fixed height though, 300dp, it can show the whole content.
In my case the content is all dynamic, very basic html, I can't use a fixed height on my layout. I also don't want to be loading it into a webview as it'll be simple html.
I've tried writing the rootview, as well as the textview, and both behave the same.
Is there any way to do this and use wrap content?
I've attached images for both.
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()
}
Layout
<?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>
Wrap Content on TextView
300dp on Textview
Upvotes: 1
Views: 237
Reputation: 39191
The issue here was that the TextView
was not getting a chance to lay itself out again, and resize to fit the new text, before the draw()
call happened after setting that text.
Though we found that incorporating a slight delay before the draw would work, that's kinda hacky, as we're really just guessing at an appropriate interval.
Instead, we can queue the draw and subsequent operations to occur right after the layout, by moving the draw()
and following calls into a Runnable
, and calling post()
on the TextView
with that after setting the text.
Upvotes: 1