0

I'm having an issue with the rendering of PDF images. I'm using editable PDFs and these annotations are not printed when I generate the bitmap. This problem is very specific, and I would prefer not to use other libraries than PdfRenderer. I think the images speak for themselves.

The page i'm trying to render: Good

What I get (sorry for the size but it's for thumbnail):

enter image description here

Here's my code:

    private fun pdfToBitmap(pdfFile: File) {
        if (pdfFile.extension == "pdf") {
            var bitmap: Bitmap? = null
            try {
                val renderer =
                    PdfRenderer(
                        ParcelFileDescriptor.open(
                            pdfFile,
                            ParcelFileDescriptor.MODE_READ_ONLY
                        )
                    )
                val pageCount = renderer.pageCount
                if (pageCount > 0) {
                    val page = renderer.openPage(0)

                    bitmap = Bitmap.createBitmap(page.width/2, page.height/2, Bitmap.Config.ARGB_8888 )        //On change la resolution de la preview

                    page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_PRINT)
                    page.close()
                    renderer.close()

                    var file: File? = null

                    try {
                        file = File(
                            cacheDir,                     //Les miniatures sont enregistré ici
                            pdfFile.name
                        )
                        file.createNewFile()

                        //Convert bitmap to byte array
                        val bos = ByteArrayOutputStream()
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                            bitmap.compress(
                                Bitmap.CompressFormat.WEBP_LOSSY,
                                100,
                                bos
                            )
                        }else{
                            bitmap.compress(
                                Bitmap.CompressFormat.WEBP,
                                100,
                                bos
                            )
                        }

                        val bitmapdata = bos.toByteArray()


                        //write the bytes in file
                        val fos = FileOutputStream(file)
                        fos.write(bitmapdata)
                        fos.flush()
                        fos.close()
                        //println("Une miniature a été cree pour "+pdfFile.name)
                    } catch (e: Exception) {
                        e.printStackTrace()
                        println(e)
                    }


                }
            } catch (ex: Exception) {
                ex.printStackTrace()
            }
        }
    }

Thanks a lot

Bam Bou
  • 95
  • 1
  • 7

0 Answers0