【问题标题】:How can I Open a PDF document using PDFView inside an AlertDialog?如何在 AlertDialog 中使用 PDFView 打开 PDF 文档?
【发布时间】:2020-09-12 11:08:38
【问题描述】:

我正在创建一个人们可以与之共享文档的应用程序。我想以一种方式创建它,当用户单击文档时,它会在应用程序内部打开,而不是使用 WPS 等第三方应用程序下载和打开它。我希望使用警报对话框中的 PDFView 打开文档。我使用的这段代码只创建了一个 alertDialog,但它不加载 PDF。关于如何加载 PDF 的任何想法?可行吗?

holder.postDocument.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.AlertDialog);
            builder.setTitle("Post document");

            final String pdfUrl = "https://www.tutorialspoint.com/computer_programming/computer_programming_tutorial.pdf";
            final PDFView pdfView = new PDFView(mContext, null);
            pdfView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            pdfView.fromUri(Uri.parse(post.getPostdocument() pdfUrl)).load();
            builder.setView(pdfView);

            builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(final DialogInterface dialog, int which) {
                 
                 dialog.dismiss();
                   

                }
            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });

            builder.show();
        }
    });

【问题讨论】:

    标签: android android-alertdialog androidpdfviewer


    【解决方案1】:

    1 - 首先您需要下载 PDF 文件并将其存储到您的手机存储中:

    @SuppressLint("StaticFieldLeak")
        private class DownloadFile extends AsyncTask<String, Integer, String> {
    
            String savedFilePath = null;
            ProgressDialog progressDialog;
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                StrictMode.setVmPolicy(builder.build());
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setTitle("Downloading PDF");
                progressDialog.setMessage("Please wait (0%)");
                progressDialog.show();
            }
    
            @Override
            protected String doInBackground(String... urlParams) {
                int count;
                String fileName = urlParams[1] + ".pdf";
                File storageDir = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                                + "/PDF_FOLDER/");
                boolean success = true;
                if (!storageDir.exists()) {
                    success = storageDir.mkdirs();
                }
                if (success) {
                    File file = new File(storageDir, fileName);
                    savedFilePath = file.getAbsolutePath();
                    if (!file.exists()) {
                        try {
                            URL url = new URL(urlParams[0]);
                            URLConnection conexion = url.openConnection();
                            conexion.connect();
                            int lengthOfFile = conexion.getContentLength();
                            InputStream input = new BufferedInputStream(url.openStream());
                            OutputStream output = new FileOutputStream(file);
                            byte[] data = new byte[1024];
                            long total = 0;
                            while ((count = input.read(data)) != -1) {
                                total += count;
                                publishProgress((int) (total * 100 / lengthOfFile));
                                output.write(data, 0, count);
                            }
                            output.flush();
                            output.close();
                            input.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
    
                }
                return savedFilePath;
            }
    
            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
                progressDialog.setMessage("Please wait (" + values[0] + "%)");
            }
    
            @Override
            protected void onPostExecute(String pdfPath) {
                super.onPostExecute(pdfPath);
                if (pdfPath != null && !pdfPath.isEmpty()) {
                    progressDialog.dismiss();
                    showPDFDialog(pdfPath);
                }
            }
        }
    

    2 - 下载过程完成后,在自定义对话框中显示 PDF,如下所示:

      public void showPDFDialog(String pdfPath) {
            Dialog dialog = new Dialog(MainActivity.this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            assert dialog.getWindow() != null;
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.dialog_view);
            PDFView pdfView = dialog.findViewById(R.id.pdfView);
            if (pdfPath != null && FileUtils.isFileExists(FileUtils.getFileByPath(pdfPath)))
                pdfView.fromFile(FileUtils.getFileByPath(pdfPath)).defaultPage(0)
                        .enableAnnotationRendering(true)
                        .scrollHandle(new DefaultScrollHandle(this))
                        .load();
            else ToastUtils.showShort("FILE NOT EXISTS");
            dialog.show();
        }
    

    3 - 对话框 XML:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:gravity="center"
                android:text="Post document"
                android:textAllCaps="true"
                android:textColor="@android:color/black"
                android:textSize="24sp"
                android:textStyle="bold" />
    
            <com.github.barteksc.pdfviewer.PDFView
                android:id="@+id/pdfView"
                android:layout_width="match_parent"
                android:layout_height="400dp" />
    
            <Button
                android:id="@+id/cancel_action"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="end"
                android:layout_margin="4dp"
                android:background="@null"
                android:text="Cancel" />
        </LinearLayout>
    </RelativeLayout>
    

    4 - 像这样调用下载类:

     final String pdfUrl = "https://www.tutorialspoint.com/computer_programming/computer_programming_tutorial.pdf";
        
    
     new DownloadFile().execute(pdfUrl, "PDF_NAME_");
    

    结果:

    使用的库:

    implementation 'com.blankj:utilcodex:1.29.0'
    implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
    

    权限:

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    

    【讨论】:

    • 谢谢@Mouaad。让我试试这个。
    • @willy 确保您已添加必要的权限并授予存储权限
    • 你好@Mouaad,我实现了代码,但是在启动进度对话框后,文档需要下载。它仍然为零。手机已连接到互联网,可能是什么问题?
    • 没有下载,只有0%。
    • 我也添加了权限,但还是没有
    猜你喜欢
    • 1970-01-01
    • 2019-02-25
    • 2021-05-18
    • 2010-10-21
    • 2018-08-20
    • 2020-04-21
    • 2020-02-26
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多