I am creating a PDF from the contents of a scrollview. Each page, however, has a blank space at the bottom. I am calculating the height based on the newAttributes passed to the onLayout method of PrintDocumentAdapter.
val pageSize = newAttributes.mediaSize?.heightMils
This is what I am using to set the height of bitmap but seems like bitmap is shorter than the actual page size and hence there is blank space at the bottom.
I checked the conversion of pixels to mils and vice-versa is applied where it should be. Since I am using the height from media attribute to print to the pdf page, I expected the entire page to have contents. What I might be missing here?
Code:
printManager.print(jobName, object : PrintDocumentAdapter() {
override fun onLayout(oldAttributes: PrintAttributes?, newAttributes: PrintAttributes, cancellationSignal: CancellationSignal?, callback: LayoutResultCallback?, extras: Bundle?) {
pdfDocument = PrintedPdfDocument(context, newAttributes)
if (cancellationSignal?.isCanceled == true) {
callback?.onLayoutCancelled()
return
}
// This value is in mils, which is thousands of an inch
pageSize = newAttributes.mediaSize?.heightMils!!
// Convert to mils
val contentSize = scrollView.getChildAt(0).height * 10
numberOfPages = ceil(((contentSizeMils / pageSize).toDouble())).toInt()
if (numberOfPages > 0) {
PrintDocumentInfo.Builder(jobName)
.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(numberOfPages)
.build()
.also { info ->
callback?.onLayoutFinished(info, true)
}
} else {
callback?.onLayoutFailed("Page count calculation failed.")
}
}
override fun onWrite(pages: Array<PageRange>?, destination: ParcelFileDescriptor?, cancellationSignal: CancellationSignal?, callback: WriteResultCallback?) {
for (i in 0 until numberOfPages) {
// Convert to pixel
val printableHeight = pageSize / 10
val pageInfo = PdfDocument.PageInfo.Builder(scrollView.getChildAt(0).width, printableHeight, i).create()
val page = pdfDocument?.startPage(pageInfo)
val canvas = page?.canvas
// Calculate the portion of the content to be drawn for this page
val start = i * printableHeight
val end = ((i + 1) * printableHeight)
// Create bitmap of the portion of the scroll view content for this page
val bitmap = Bitmap.createBitmap(scrollView.getChildAt(0).width, end - start, Bitmap.Config.ARGB_8888)
val contentCanvas = Canvas(bitmap)
contentCanvas.translate(0f, (-start).toFloat()) // Translate canvas to the appropriate position
scrollView.getChildAt(0).draw(contentCanvas)
// Draw the bitmap onto the canvas
canvas?.drawBitmap(bitmap, 0f, 0f, null)
pdfDocument?.finishPage(page)
}
try {
pdfDocument?.writeTo(FileOutputStream(destination?.fileDescriptor))
} catch (e: IOException) {
callback?.onWriteFailed(e.toString())
return
} finally {
pdfDocument?.close()
pdfDocument = null
}
callback?.onWriteFinished(pages)
}