簡體   English   中英

如何使用 PdfRenderer 從 Android 應用程序內的內部存儲中渲染 PDF 文件

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

我試圖在將 PDF 上傳到服務器之前向用戶提供預覽。 我正在使用 PdfRenderer。 我只是為了預覽第一頁。 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)

這是我的代碼:

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

找到了修復,路徑需要是 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM