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

后端 未结 8 748
说谎
说谎 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;
        }
    
    0 讨论(0)
  • 2020-12-07 19:35

    from below code, you can extract all pages as image (PNG) format from PDF using PDFRender:

    // This method is used to extract all pages in image (PNG) format.
        private void getImagesFromPDF(File pdfFilePath, File DestinationFolder) throws IOException {
    
            // Check if destination already exists then delete destination folder.
            if(DestinationFolder.exists()){
                DestinationFolder.delete();
            }
    
            // Create empty directory where images will be saved.
            DestinationFolder.mkdirs();
    
            // Reading pdf in READ Only mode.
            ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(pdfFilePath, ParcelFileDescriptor.MODE_READ_ONLY);
    
            // Initializing PDFRenderer object.
            PdfRenderer renderer = new PdfRenderer(fileDescriptor);
    
            // Getting total pages count.
            final int pageCount = renderer.getPageCount();
    
            // Iterating pages
            for (int i = 0; i < pageCount; i++) {
    
                // Getting Page object by opening page.
                PdfRenderer.Page page = renderer.openPage(i);
    
                // Creating empty bitmap. Bitmap.Config can be changed.
                Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(),Bitmap.Config.ARGB_8888);
    
                // Creating Canvas from bitmap.
                Canvas canvas = new Canvas(bitmap);
    
                // Set White background color.
                canvas.drawColor(Color.WHITE);
    
                // Draw bitmap.
                canvas.drawBitmap(bitmap, 0, 0, null);
    
                // Rednder bitmap and can change mode too.
                page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    
                // closing page
                page.close();
    
                // saving image into sdcard.
                File file = new File(DestinationFolder.getAbsolutePath(), "image"+i + ".png");
    
                // check if file already exists, then delete it.
                if (file.exists()) file.delete();
    
                // Saving image in PNG format with 100% quality.
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                    Log.v("Saved Image - ", file.getAbsolutePath());
                    out.flush();
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    

    You can call this method in below way:

    // Getting images from Test.pdf file.
            File source = new File(Environment.getExternalStorageDirectory() + "/" + "Test" + ".pdf");
    
            // Images will be saved in Test folder.
            File destination = new File(Environment.getExternalStorageDirectory() + "/Test");
    
            // Getting images from pdf in png format.
            try {
                getImagesFromPDF(source, destination);
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    Cheers!

    0 讨论(0)
  • 2020-12-07 19:47

    Starting from Android API 21 PdfRenderer is what you are looking for.

    0 讨论(0)
  • 2020-12-07 19:48

    To support API 8 and above, follow:

    Using this library: android-pdfview and the following code, you can reliably convert the PDF pages into images (JPG, PNG):

    DecodeServiceBase decodeService = new DecodeServiceBase(new PdfContext());
    decodeService.setContentResolver(mContext.getContentResolver());
    
    // a bit long running
    decodeService.open(Uri.fromFile(pdf));
    
    int pageCount = decodeService.getPageCount();
    for (int i = 0; i < pageCount; i++) {
        PdfPage page = decodeService.getPage(i);
        RectF rectF = new RectF(0, 0, 1, 1);
    
        // do a fit center to 1920x1080
        double scaleBy = Math.min(AndroidUtils.PHOTO_WIDTH_PIXELS / (double) page.getWidth(), //
                AndroidUtils.PHOTO_HEIGHT_PIXELS / (double) page.getHeight());
        int with = (int) (page.getWidth() * scaleBy);
        int height = (int) (page.getHeight() * scaleBy);
    
        // you can change these values as you to zoom in/out
        // and even distort (scale without maintaining the aspect ratio)
        // the resulting images
    
        // Long running
        Bitmap bitmap = page.renderBitmap(with, height, rectF);
    
        try {
            File outputFile = new File(mOutputDir, System.currentTimeMillis() + FileUtils.DOT_JPEG);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
    
            // a bit long running
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
    
            outputStream.close();
        } catch (IOException e) {
            LogWrapper.fatalError(e);
        }
    }
    

    You should do this work in the background i.e. by using an AsyncTask or something similar as quite a few methods take computation or IO time (I have marked them in comments).

    0 讨论(0)
  • 2020-12-07 19:52

    You need to have look at this open-source for project for the same requirement, that can be helpful to you to do many more things also.

    Project : PdfRenderer

    There is one Java class named PDFPage.java in pdfview package. that class have a method to get Image of the page.

    I have also implemented the same thing in my test project and the java code is here for you. I have created one method showPage which accepts the page no and zoom level and return that page as Bitmap.

    Hope this can help you. You just need to get that Project or JAR for that, Read the well-documented JAVADOC for the same and then try and implement the same as I did.

    Take your time, Happy Coding :)

    0 讨论(0)
  • 2020-12-07 19:56

    I will say you a simple trick not a complete solution.Once if you successfully rendered the pdf page you will get its bitmap from screen as follow

    View view = MuPDFActivity.this.getWindow().getDecorView();
    if (false == view.isDrawingCacheEnabled()) {
        view.setDrawingCacheEnabled(true);
    }
    Bitmap bitmap = view.getDrawingCache();
    

    Then you can save this bitmap, that is your pdf page as image in locally

    try {
        new File(Environment.getExternalStorageDirectory()+"/PDF Reader").mkdirs();
        File outputFile = new File(Environment.getExternalStorageDirectory()+"/PDF Reader", System.currentTimeMillis()+"_pdf.jpg");
        FileOutputStream outputStream = new FileOutputStream(outputFile);
    
        // a bit long running
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.close();
    } catch (IOException e) {
        Log.e("During IMAGE formation", e.toString());
    }
    

    that's all, hope you help this.

    0 讨论(0)
提交回复
热议问题