在 Android 中从 URI 渲染 PDF



我在应用程序中使用了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 制作文件吗?提前谢谢。

而不是:

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

相关内容

  • 没有找到相关文章

最新更新