Yves Kalume
01/06/2022, 9:58 AMgildor
01/06/2022, 10:05 AMBrian Guertin
01/06/2022, 6:27 PM@Composable
private fun PDFPage(
renderer: PdfRenderer,
rendererMutex: Mutex,
index: Int,
pageFit: PageFit
) {
BoxWithConstraints(Modifier.padding(HALF_PAGE_PADDING)) {
val bitmap by produceState<Bitmap?>(null) {
withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
rendererMutex.withLock {
renderer.openPage(index).use { page ->
val size = pageFit.size(constraints, page.width, page.height)
val bitmap = Bitmap.createBitmap(
size.width, size.height, Bitmap.Config.ARGB_8888
)
page.render(
bitmap,
null,
null,
PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY
)
value = bitmap
}
}
}
}
val imageBitmap = bitmap?.asImageBitmap()
if (imageBitmap == null) Box(
when (pageFit) {
PageFit.FILL_HORIZONTAL -> Modifier.fillMaxWidth()
PageFit.FILL_VERTICAL -> Modifier.fillMaxHeight()
else -> Modifier
}.aspectRatio(1f)
)
else Image(
imageBitmap,
"Page ${index + 1}",
modifier = Modifier
.thenIf(pageFit == PageFit.CONTAIN) { align(Alignment.Center) }
.shadow(4.dp)
.background(Color.White)
)
}
}
private enum class PageFit(val size: (constraints: Constraints, pageWidth: Int, pageHeight: Int) -> IntSize) {
FILL_HORIZONTAL({ constraints, pageWidth, pageHeight ->
IntSize(
constraints.maxWidth,
(constraints.maxWidth.toFloat() / pageWidth * pageHeight).roundToInt()
)
}),
FILL_VERTICAL({ constraints, pageWidth, pageHeight ->
IntSize(
(constraints.maxHeight.toFloat() / pageHeight * pageWidth).roundToInt(),
constraints.maxHeight,
)
}),
CONTAIN({ constraints, pageWidth, pageHeight ->
if (pageWidth.toFloat() / constraints.maxWidth > pageHeight.toFloat() / constraints.maxHeight) FILL_VERTICAL.size(
constraints,
pageWidth,
pageHeight
)
else FILL_HORIZONTAL.size(constraints, pageWidth, pageHeight)
})
}
allan.conda
01/06/2022, 7:19 PMBrian Guertin
01/06/2022, 9:26 PMallan.conda
01/06/2022, 9:34 PM