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()
}
}
Comments
-
shanraisshan almost 3 years
I want to generate the image(thumbnail) from pdf file just like done by WhatsApp as shown below
I have tried
- PDFBox (https://github.com/TomRoush/PdfBox-Android)
- Tika (compile 'org.apache.tika:tika-parsers:1.11')
- AndroidPdfViewer (https://github.com/barteksc/AndroidPdfViewer)
and still unable to find a way to generate image from pdf.
PDFBox:
There is a github issue that deals with this problem (https://github.com/TomRoush/PdfBox-Android/issues/3) but this is still unresolved.
Note: I am successfully able to extract image from PDF using PDFBOX
AndroidPdfViewer:
Github issue (https://github.com/barteksc/AndroidPdfViewer/issues/49)