从文件选择器获取正确的路径

时间:2019-03-18 15:39:03

标签: android uri pdfrenderer

我需要将PDF文件放入我的应用程序。我已经看过类似的问题,但没有一个起作用。 PdfReader不断抛出异常,指出:未找到文件。所以我想目录是错误的。这是我的代码:

cardViewPlan.setOnClickListener(v -> {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/pdf");
        startActivityForResult(intent, FILE_PICK_RESULT_CODE);
    });

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
        case 1: {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();

                String path = uri.getPath();
                File file = new File(path);

                txtFileName.setText(path);

                try {
                    PdfRenderer pdfRenderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));

                    Bitmap bitmap;
                    final int pageCount = pdfRenderer.getPageCount();
                    for (int i = 0; i < pageCount ; i++) {
                        PdfRenderer.Page page = pdfRenderer.openPage(i);

                        int width = getResources().getDisplayMetrics().densityDpi / 72 * page.getWidth();
                        int height = getResources().getDisplayMetrics().densityDpi / 72 * page.getHeight();
                        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

                        page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);
                        byte[] bytes = baos.toByteArray();
                        String filename = "PDF_IMG_" + UUID.randomUUID().toString() + ".jpg";                           
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
        break;

    }
}

0 个答案:

没有答案