androidandroid-jetpack-composelazycolumnandroid-compose-layout

How to convert all content of a composable to Bitmap in Android Jetpack compose?


I am trying to convert all the content of a LazyColumn to bitmap, and then export it to a pdf file.

I did find this library to take screenshots of what is showing but not for all the content. Content that was not showing is not included. So I also try to draw canvas instead, but we can not apply all styles of the content (like a markdown, custom background,...) So I am thinking that we can have a custom native Android View, it may be possible to do it, but I can't find a way to pass a composable into it.

So anyone done that before or has a solution for this?

Edit 1: I did try to use draw content in compose graphics alpha-02, but the content in the LazyColumn was unable to scroll:

    onDrawWithContent {
        val pictureCanvas = Canvas(picture.beginRecording(width, height))

        draw(this, this.layoutDirection, pictureCanvas, this.size) {
////
        }
        picture.endRecording()

        drawIntoCanvas { canvas -> canvas.nativeCanvas.drawPicture(picture) }
      }

Solution

  • I had the same requirement like you and wanted to be able to achieve capturing all screen. So I was able to achieve this inside a scrollable view with Capturable

    The component which needs to be captured should be placed inside Capturable composable as follows:

    @Composable
    fun TicketScreen() {
        // I was able to capture the full width of the composable which was not visible on the screen with a scroll modifier on top of the Capturable for example:
        Column(modifier = Modifier.horizontalScroll(rememberScrollState())) {
            Capturable(
                modifier = Modifier,
                controller = controller,
                onCaptured = { bitmap, error ->
                    if (state.printVides) {
                        onEvent(ScanPrintEvent.SetImageBitmapVides(bitmap?.asAndroidBitmap()))
                    } else {
                        onEvent(ScanPrintEvent.SetImageBitmapNormal(bitmap?.asAndroidBitmap()))
                    }
                }
            ) {
               YourComposable()
            }
        }
    }