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

后端 未结 8 749
说谎
说谎 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:58

    Using Android default libraries like AppCompat, you can convert all the PDF pages into images. This way is very fast and optimized. The below code is for getting separate images of a PDF page. It is very fast and quick.

    I have implemented like below:

    ParcelFileDescriptor fileDescriptor = ParcelFileDescriptor.open(new File("pdfFilePath.pdf"), MODE_READ_ONLY);
        PdfRenderer renderer = new PdfRenderer(fileDescriptor);
        final int pageCount = renderer.getPageCount();
        for (int i = 0; i < pageCount; i++) {
            PdfRenderer.Page page = renderer.openPage(i);
            Bitmap bitmap = Bitmap.createBitmap(page.getWidth(), page.getHeight(),Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            canvas.drawColor(Color.WHITE);
            canvas.drawBitmap(bitmap, 0, 0, null);
            page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            page.close();
    
            if (bitmap == null)
                return null;
    
            if (bitmapIsBlankOrWhite(bitmap))
                return null;
    
            String root = Environment.getExternalStorageDirectory().toString();
            File file = new File(root + filename + ".png");
    
            if (file.exists()) file.delete();
            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();
            }
        }
    

    =======================================================

    private static boolean bitmapIsBlankOrWhite(Bitmap bitmap) {
        if (bitmap == null)
            return true;
    
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        for (int i =  0; i < w; i++) {
            for (int j = 0; j < h; j++) {
                int pixel =  bitmap.getPixel(i, j);
                if (pixel != Color.WHITE) {
                    return false;
                }
            }
        }
        return true;
    }
    

    I have already posted it in another question :P

    Link is - https://stackoverflow.com/a/58420401/12228284

    0 讨论(0)
  • 2020-12-07 20:01

    Finally I found very simple solution to this, Download library from here.

    Use below code to get images from PDF:

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.RectF;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Environment;
    import android.provider.MediaStore;
    
    import org.vudroid.core.DecodeServiceBase;
    import org.vudroid.core.codec.CodecPage;
    import org.vudroid.pdfdroid.codec.PdfContext;
    
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.util.ArrayList;
    
    /**
     * Created by deepakd on 06-06-2016.
     */
    public class PrintUtils extends AsyncTask<Void, Void, ArrayList<Uri>>
    {
        File file;
        Context context;
        ProgressDialog progressDialog;
    
        public PrintUtils(File file, Context context)
        {
    
            this.file = file;
            this.context = context;
        }
    
        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            // create and show a progress dialog
            progressDialog = ProgressDialog.show(context, "", "Please wait...");
            progressDialog.show();
        }
    
        @Override
        protected ArrayList<Uri> doInBackground(Void... params)
        {
            ArrayList<Uri> uris = new ArrayList<>();
    
            DecodeServiceBase decodeService = new DecodeServiceBase(new PdfContext());
            decodeService.setContentResolver(context.getContentResolver());
            // a bit long running
            decodeService.open(Uri.fromFile(file));
            int pageCount = decodeService.getPageCount();
            for (int i = 0; i < pageCount; i++)
            {
                CodecPage page = decodeService.getPage(i);
                RectF rectF = new RectF(0, 0, 1, 1);
                // do a fit center to A4 Size image 2480x3508
                double scaleBy = Math.min(UIUtils.PHOTO_WIDTH_PIXELS / (double) page.getWidth(), //
                        UIUtils.PHOTO_HEIGHT_PIXELS / (double) page.getHeight());
                int with = (int) (page.getWidth() * scaleBy);
                int height = (int) (page.getHeight() * scaleBy);
                // Long running
                Bitmap bitmap = page.renderBitmap(with, height, rectF);
                try
                {
                    OutputStream outputStream = FileUtils.getReportOutputStream(System.currentTimeMillis() + ".JPEG");
                    // a bit long running
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    outputStream.close();
                   // uris.add(getImageUri(context, bitmap));
                    uris.add(saveImageAndGetURI(bitmap));
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            return uris;
        }
    
        @Override
        protected void onPostExecute(ArrayList<Uri> uris)
        {
            progressDialog.hide();
            //get all images by uri 
            //ur implementation goes here
        }
    
    
    
    
        public void shareMultipleFilesToBluetooth(Context context, ArrayList<Uri> uris)
        {
            try
            {
                Intent sharingIntent = new Intent();
                sharingIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                sharingIntent.setType("image/*");
               // sharingIntent.setPackage("com.android.bluetooth");
                sharingIntent.putExtra(Intent.EXTRA_STREAM, uris);
                context.startActivity(Intent.createChooser(sharingIntent,"Print PDF using..."));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    
    
    
    
    
        private Uri saveImageAndGetURI(Bitmap finalBitmap) {
            String root = Environment.getExternalStorageDirectory().toString();
            File myDir = new File(root + "/print_images");
            myDir.mkdirs();
            String fname = "Image-"+ MathUtils.getRandomID() +".jpeg";
            File file = new File (myDir, fname);
            if (file.exists ()) file.delete ();
            try {
                FileOutputStream out = new FileOutputStream(file);
                finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                out.flush();
                out.close();
    
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return Uri.parse("file://"+file.getPath());
        }
    
    }
    

    FileUtils.java

    package com.airdata.util;
    
    import android.net.Uri;
    import android.os.Environment;
    import android.support.annotation.NonNull;
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    
    /**
     * Created by DeepakD on 21-06-2016.
     */
    public class FileUtils
    {
    
        @NonNull
        public static OutputStream getReportOutputStream(String fileName) throws FileNotFoundException
    {
        // create file
        File pdfFolder = getReportFilePath(fileName);
        // create output stream
        return new FileOutputStream(pdfFolder);
    }
    
        public static Uri getReportUri(String fileName)
        {
            File pdfFolder = getReportFilePath(fileName);
            return Uri.fromFile(pdfFolder);
        }
        public static File getReportFilePath(String fileName)
        {
            /*File file = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOWNLOADS), FileName);*/
            File file = new File(Environment.getExternalStorageDirectory() + "/AirPlanner/Reports");
            //Create report directory if does not exists
            if (!file.exists())
            {
                //noinspection ResultOfMethodCallIgnored
                file.mkdirs();
            }
            file = new File(Environment.getExternalStorageDirectory() + "/AirPlanner/Reports/" + fileName);
            return file;
        }
    }
    

    You can view converted images in Gallery or in SD card. Please let me know if you need any help.

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