How to convert a PDF page to an image in Android?

后端 未结 8 787
说谎
说谎 2020-12-07 19:33

All I need to do is take a (locally saved) PDF-document and convert one or all of it\'s pages to image format like JPG or PNG.

I\'ve tr

8条回答
  •  长情又很酷
    2020-12-07 19:34

    Use the lib https://github.com/barteksc/PdfiumAndroid

    public Bitmap getBitmap(File file){
     int pageNum = 0;
                PdfiumCore pdfiumCore = new PdfiumCore(context);
                try {
                    PdfDocument pdfDocument = pdfiumCore.newDocument(openFile(file));
                    pdfiumCore.openPage(pdfDocument, pageNum);
    
                    int width = pdfiumCore.getPageWidthPoint(pdfDocument, pageNum);
                    int height = pdfiumCore.getPageHeightPoint(pdfDocument, pageNum);
    
    
                    // ARGB_8888 - best quality, high memory usage, higher possibility of OutOfMemoryError
                    // RGB_565 - little worse quality, twice less memory usage
                    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
    
                    pdfiumCore.closeDocument(pdfDocument); // important!
                    return bitmap;
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                return null;
    }
    
     public static ParcelFileDescriptor openFile(File file) {
            ParcelFileDescriptor descriptor;
            try {
                descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            }
            return descriptor;
        }
    

提交回复
热议问题