如何在Android中将PDF页面转换为图像?

时间:2012-05-22 08:24:59

标签: java android pdf

我需要做的就是将(本地保存的)PDF-document将其中的一个或全部页面转换为图像格式,如JPG或PNG。

我已经尝试了大量的PDF渲染/查看解决方案,例如APV PDF ViewerAPDFViewerdroidreaderandroid-pdfMuPdf以及其他许多解决方案到目前为止,如何将pdf页面转换为图像?

编辑:此外,我宁愿使用PDF到图像转换器而不是我需要编辑的PDF渲染器,以将PDF转换为图像。

8 个答案:

答案 0 :(得分:9)

您需要查看这个开源项目以获得相同的要求,这对您做更多的事情也很有帮助。

项目:PdfRenderer

pdfview包中有一个名为PDFPage.java的Java类。该类有一个方法来获取页面的图像。

我在我的测试项目中也实现了同样的东西,java代码是here for you。我创建了一个方法showPage,它接受​​页面号和缩放级别,并将该页面返回为Bitmap

希望这可以帮到你。您只需要获得该项目或JAR,阅读记录良好的JAVADOC,然后尝试实现与我相同的操作。

慢慢来,快乐编码:)

答案 1 :(得分:9)

要支持API 8及更高版本,请按以下步骤操作:

使用此库:android-pdfview和以下代码,您可以可靠地将PDF页面转换为图像(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);
    }
}

你应该在后台工作,即使用AsyncTask或类似的东西,因为很多方法需要计算或IO时间(我在评论中标记了它们)。

答案 2 :(得分:6)

从Android API 21 PdfRenderer开始,您正在寻找。

答案 3 :(得分:2)

使用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;
    }

答案 4 :(得分:1)

我会说你一个简单的技巧而不是一个完整的解决方案。如果你成功地渲染了pdf页面,你将从屏幕上获得它的位图,如下所示

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

然后你可以保存这个位图,即你的pdf页面作为本地的图像

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());
}

这一切,希望你帮助这个。

答案 5 :(得分:1)

最后我找到了非常简单的解决方案, 从here下载库。

使用以下代码从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;
    }
}

您可以在图库或SD卡中查看转换后的图像。如果您需要任何帮助,请告诉我。

答案 6 :(得分:1)

使用Android默认库(例如AppCompat),您可以将所有PDF页面转换为图像。这种方法非常快速且经过优化。 以下代码用于获取PDF页面的单独图像。速度非常快。

我已经实现了以下内容:

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;
}

我已经在另一个问题中张贴了它:P

链接为-https://stackoverflow.com/a/58420401/12228284

答案 7 :(得分:0)

从下面的代码中,您可以使用PDFRender从PDF中提取所有页面为图像(PNG)格式:

0    20
1    21
2    19
3    18
Name: Age, dtype: int64

您可以通过以下方式调用此方法:

// 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();
            }
        }
    }

干杯!