philipplackner / PDF-RendererCompose

21 stars 1 forks source link

Exception: java.lang.IllegalStateException: Current page not closed #1

Open TechMatrixDeveloper opened 2 months ago

TechMatrixDeveloper commented 2 months ago

Code Example with Issue:

return@withContext (0 until pageCount).map { index ->
    async {
        openPage(index).use { page ->
            val bitmap = Bitmap.createBitmap(
                page.width,
                page.height,
                Bitmap.Config.ARGB_8888
            )

            val canvas = Canvas(bitmap).apply {
                drawColor(Color.WHITE)
                drawBitmap(bitmap, 0f, 0f, null)
            }

            page.render(
                bitmap,
                null,
                null,
                PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY
            )

            bitmap
        }
    }
}.awaitAll()  // Causes "Current page not closed" error due to concurrent page access

i just do and it's work

return@withContext (0 until pageCount).map { index ->
    async {
        openPage(index).use { page ->
            val bitmap = Bitmap.createBitmap(
                page.width,
                page.height,
                Bitmap.Config.ARGB_8888
            )

            val canvas = Canvas(bitmap).apply {
                drawColor(Color.WHITE)
            }

            page.render(
                bitmap,
                null,
                null,
                PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY
            )

            bitmap
        }
    }.await()  // Renders each page sequentially to prevent exception
}

is this right way?

This error occurs when using Android's PdfRenderer, which only allows one page to be open at a time. The issue arises when pages are opened concurrently using async, causing the application to crash.

Problem: When rendering PDF pages asynchronously with .awaitAll(), the code tries to open multiple pages at once, but PdfRenderer requires each page to be closed before opening another.

Fix: Switching from .awaitAll() to .await() ensures that pages are opened and rendered sequentially, preventing the crash. However, this makes the rendering process slower since it loses concurrency.

AhmerAfzal1 commented 2 months ago

How to zoom by three times by double tab ?