简体   繁体   English

如何使用 PdfRenderer 从 Android 应用程序内的内部存储中渲染 PDF 文件

[英]How to render PDF file from Internal storage inside Android App using PdfRenderer

I am trying to give a preview of PDF to the user before uploading it to a server.我试图在将 PDF 上传到服务器之前向用户提供预览。 I am using PdfRenderer.我正在使用 PdfRenderer。 I just to give the preview of the 1st page.我只是为了预览第一页。 On Start, I am calling the file chooser function that lets you select a pdf file from Internal memory, and on ActivityResult the render function is called, however, I am facing an error On Start, I am calling the file chooser function that lets you select a pdf file from Internal memory, and on ActivityResult the render function is called, however, I am facing an error

I/System.out: Cursor= android.content.ContentResolver$CursorWrapperInner@a8d29d4
    Uri String= content://com.adobe.scan.android.documents/document/root%3A23
    File pathcontent://com.adobe.scan.android.documents/document/root%3A23
W/System.err: java.lang.IllegalArgumentException: Invalid page index
        at android.graphics.pdf.PdfRenderer.throwIfPageNotInDocument(PdfRenderer.java:282)
        at android.graphics.pdf.PdfRenderer.openPage(PdfRenderer.java:229)
        at com.ay404.androidfileloaderreader.CustomFunc.Main2Activity.openPdfFromStorage(Main2Activity.java:56)

Here is my code:这是我的代码:

  @RequiresApi(api=Build.VERSION_CODES.LOLLIPOP)
        private void openPdfFromStorage(Uri uri,String filename) throws IOException {
            File fileCopy = new File(getCacheDir(), filename);//anything as the name
            copyToCache(fileCopy, uri);
            ParcelFileDescriptor fileDescriptor =
                    ParcelFileDescriptor.open(fileCopy,
                            ParcelFileDescriptor.MODE_READ_ONLY);
            mPdfRenderer = new PdfRenderer(fileDescriptor);
            mPdfPage = mPdfRenderer.openPage(1);
             Bitmap bitmap = Bitmap.createBitmap(mPdfPage.getWidth(),
                    mPdfPage.getHeight(),
                    Bitmap.Config.ARGB_8888);//Not RGB, but ARGB
            mPdfPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            imageView.setImageBitmap(bitmap);
        }

void copyToCache(File file,Uri uri) throws IOException {
        if (!file.exists()) {

            InputStream input = getContentResolver().openInputStream(uri);
            FileOutputStream output = new FileOutputStream(file);
            byte[] buffer = new byte[1024];
            int size;

            while ((size = input.read(buffer)) != -1) {
                output.write(buffer, 0, size);
            }

            input.close();
            output.close();
        }
    }
RequiresApi(api=Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            filePath = data.getData();
            Uri uri = data.getData();
            String uriString=uri.toString();
            File myFile=new File(uriString);
            String displayName=null;
            Cursor cursor=null;
            Log.e("URI: ", uri.toString());
            try {

                if (uriString.startsWith("content://")) {

                    try {
                        cursor=getApplicationContext().getContentResolver().query(uri, null, null, null, null);
                        System.out.println("Cursor= " + cursor);
                        System.out.println("Uri String= " + uriString);
                        System.out.println("File path" + data.getData());

                        if (cursor != null && cursor.moveToFirst()) {
                            displayName=cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));

                            openPdfFromStorage(uri,displayName);
                            File imgFile=new File(String.valueOf(data.getData()));

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        cursor.close();
                    }
                } else if (uriString.startsWith("file://")) {

                    System.out.println("Uri String= " + uriString);
                    System.out.println("File path" + myFile.getAbsolutePath());
                    displayName=myFile.getName();
                    try {
                        openPdfFromStorage(uri,displayName);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


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

        }
    }

    private void fileChoser(){
        Intent intent=new Intent();
        intent.setType("application/pdf");
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST);
    }

    @Override
    protected void onStart() {
        super.onStart();
        fileChoser();
    }
}

Found the fix, the path needs to be static, therefore, I am copying the files to cache and then opening them from cache location找到了修复,路径需要是 static,因此,我将文件复制到缓存,然后从缓存位置打开它们

private void showPdf(String base64, String filename) {

        String fileName = "test_pdf ";

        try {

            
            final File dwldsPath = new File(this.getExternalFilesDir(String.valueOf(this.getCacheDir()))+"/"+filename);
            Log.d("File path", String.valueOf(dwldsPath));
            byte[] pdfAsBytes = Base64.decode(base64, 0);
            FileOutputStream os;
            os = new FileOutputStream(dwldsPath, false);
            os.write(pdfAsBytes);
            os.flush();
            os.close();
            Uri uri = FileProvider.getUriForFile(this,
                    BuildConfig.APPLICATION_ID + ".provider",
                    dwldsPath);
            fileName="";
            String mime = this.getContentResolver().getType(uri);

            openPDF(String.valueOf(dwldsPath),fileName);
      

        } catch(Exception e){
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
        }

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 android studio 删除 android 应用程序中的内部存储文件? - How to delete internal storage file in android app using android studio? 如何从 firebase 存储链接在我的应用程序(android studio,JAVA)中打开 pdf 文件 - How to open pdf file inside my app (android studio, JAVA) from firebase storage link 如何使用内部存储器中的其他应用程序读取pdf文件? - How to read a pdf file using other App from internal memory? 如何从 android 的内部存储器中移动文件 a? - How to move file a from internal storage of android? 如何在Android上将文件从内部应用程序存储移动/重命名为外部存储? - How to move/rename file from internal app storage to external storage on Android? 从内部存储Android应用程序访问Excel文件 - Excel file access from internal storage android app 从内部存储,Android Studio(JAVA)播放音频文件的应用程序 - App that plays audio file from internal Storage, Android Studio (JAVA) 如何从 android 存储中选择 pdf 文件 - How to choose pdf file from android storage 如何为我的 Android 应用程序创建内部存储文件的共享首选项? - How to create shared preferences to internal storage file for my Android app? 我们如何从Firebase下载Android Studio中的文件(pdf),使其不出现在手机的内部存储中? - How can we download file(pdf) in android studio from firebase such that it doesn't appear in phone's internal storage?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM