Generate Thumbnail of Pdf in Android

21,825
val file = Constant.allMediaList[position]
val filename = Environment.getExternalStoragePublicDirectory(file)
if (file != null) {
    if (file.endsWith(".pdf")){
        val fd :ParcelFileDescriptor= ParcelFileDescriptor.open(filename,ParcelFileDescriptor.MODE_READ_WRITE)
        val pageNum: Int  = 0;
        val pdfiumCore: PdfiumCore  = PdfiumCore(mContext);
        try {
            val pdfDocument: PdfDocument = pdfiumCore.newDocument(fd);
            pdfiumCore.openPage(pdfDocument, pageNum);
            val width:  Int  = pdfiumCore.getPageWidthPoint(pdfDocument, pageNum);
            val height:  Int = pdfiumCore.getPageHeightPoint(pdfDocument, pageNum);

            // ARGB_8888 - best quality, high memory usage, higher possibility of OutOfMemoryError
            // RGB_565 - little worse quality, twice less memory usage
            val bitmap: Bitmap = Bitmap.createBitmap(width, height,
                  Bitmap.Config.RGB_565);
            pdfiumCore.renderPageBitmap(pdfDocument, bitmap, pageNum, 0, 0,width, height);
            //if you need to render annotations and form fields, you can use
            //the same method above adding 'true' as last param

            Glide.with(mContext)
                .load(bitmap).into(holder.thumbnail)

            pdfiumCore.closeDocument(pdfDocument); // important!
        } catch(ex: IOException) {
            ex.printStackTrace();
            Toast.makeText(mContext,"failed",Toast.LENGTH_LONG).show()
        }

    }
Share:
21,825
shanraisshan
Author by

shanraisshan

linkedin.com/in/shanraisshan/

Updated on June 18, 2021

Comments