从Android中的URI渲染PDF?

时间:2018-03-13 01:19:37

标签: android pdf pdfrenderer

我在我的应用中使用Android Render,但是我从URI获取PDF文件时遇到了问题。

以下是我如何获取文件的URI:

 public void performFileSearch() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

    intent.addCategory(Intent.CATEGORY_OPENABLE);

    intent.setType("application/pdf");

    startActivityForResult(intent, READ_REQUEST_CODE);
}

@Override
public void onActivityResult(int requestCode, int resultCode,
                             Intent resultData) {
    if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
         uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            pageNumber = 0;
            render(uri);

        }
    }
}

然后在render(Uri uri)

private void render(Uri uri) {

    try {
        img = (ImageView) findViewById(R.id.image);
        int width = img.getWidth();
        int height = img.getHeight();
        previous.setText(uri.toString());
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
        File file = new File(uri.getPath());
        PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

        if(currentpage<0){
            currentpage =0;

        }else if(currentpage>renderer.getPageCount()){


            currentpage = renderer.getPageCount() -1;

            Matrix matrix = img.getImageMatrix();

            Rect rect= new Rect(0,0, width , height);

            renderer.openPage(currentpage).render(bitmap,rect,matrix , PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY );

            img.setImageMatrix(matrix);
            img.setImageBitmap(bitmap);
            img.invalidate();

        }


    } catch (Exception e) {

        e.printStackTrace();
         Toast.makeText(getApplicationContext(), "Nope", Toast.LENGTH_LONG);

    }

}

活动仅显示白屏。我想问题是从URI创建文件。你知道如何从URI获取文件吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

代替:

File file = new File(uri.getPath());
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

使用这个:

ParcelFileDescriptor fileDescriptor =context.getContentResolver().openFileDescriptor(uri, "r");
PdfRenderer renderer = new PdfRenderer(fileDescriptor, ParcelFileDescriptor.MODE_READ_ONLY);