English 中文(简体)
如何将 PDF 页面转换为 Android 的图像?
原标题:How to convert a PDF page to an image in Android?

我只需要将 PDF-document (本地保存) /PDF-document (本地保存) 和 将一个或全部页面转换为图像 格式, 如 JPG 或 PNG 。

我尝试过很多PDFRendering/view 解决方案,例如 < a href="http://code.google.com/p/apv/" rel="noreferrer" >APV PDF Viewer , APV PDF Viewer , < a hrefref="http://code.gogle.com/p/apdfviewer < a hrefrefref=", < a hrefref="https://stackoverflow.com/10070137/pdf-viewer-usinging-mulibrary/ a homen_library > a mum71078 > a fillage a mus mus much12/

我宁愿用PDF转换成图像转换器, 也不愿用PDF转换成图像。

问题回答

为支持API 8及以上,如下:

使用此库 : < a href=" https://github.com/JoanZapata/android-pdfview" rel="noreferrer" >andandroid-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);
    }
}

您应该在背景中做这项工作, 即使用 < code> AsyncTask 或类似一些方法的类似方法进行计算或 IO 时间( 我在批注中标注了它们) 。

从Android API 21PdfRenderer 是你们要找的。

使用 lib < a href=" "https://github.com/barteksc/Pdfium Android" rel=“noreferrer" >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;
    }

使用像 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)中张贴了它:

链接是 - < a href="https://stackoverflow.com/a/584204001/12228284" >https://stackoverflow.com/a/5840401/12228284

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

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

您可以在下面将此方法命名为 :

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

干杯! 干杯! 干杯! 干杯!

我将说,你是一个简单的把戏,而不是一个完整的解决方案。一旦你成功完成 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());
}

希望你们能帮上忙

Finally I found very simple solution to this, Download library from 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());
    }

}

文件Utils.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;
    }
}

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

After going through and trying all the answers, none worked for me for all the PDF files. Rendering issues were there in custom font PDF files. Then I tried using library. I took inspiration from NickUncheck s answer for getting Images from all PDF pages.

该守则如下:

在您的应用程序构建中. gradle 文件添加以下依赖性 :

implementation  com.github.barteksc:android-pdf-viewer:3.2.0-beta.1 

将 PDF 页面转换为图像的代码 :

      public static List<Bitmap> renderToBitmap(Context context, String filePath) {
            List<Bitmap> images = new ArrayList<>();
            PdfiumCore pdfiumCore = new PdfiumCore(context);
            try {
                File f = new File(pdfPath);
                ParcelFileDescriptor fd = ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
                PdfDocument pdfDocument = pdfiumCore.newDocument(fd);
                final int pageCount = pdfiumCore.getPageCount(pdfDocument);
                for (int i = 0; i < pageCount; i++) {
                    pdfiumCore.openPage(pdfDocument, i);
                    int width = pdfiumCore.getPageWidthPoint(pdfDocument, i);
                    int height = pdfiumCore.getPageHeightPoint(pdfDocument, i);
                    Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                    pdfiumCore.renderPageBitmap(pdfDocument, bmp, i, 0, 0, width, height);
                    images.add(bmp);
                }
                pdfiumCore.closeDocument(pdfDocument);
            } catch(Exception e) {
                //todo with exception
            }
     return images;
   }

到目前为止,它为我工作 所有PDF文件,我试过。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签