Android的 - 里面的WebView加载PDF [英] Android - Load PDF inside webview

查看:100
本文介绍了Android的 - 里面的WebView加载PDF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的WebView code,我想有可能有PDF文件打开时,用户点击一个PDF链接。这里是code,你能告诉我,我必须把这个PDF区域里面?我尝试了很多不同的方式,我不能让PDF查看的。感谢您的帮助。

  webview.setWebViewClient(新WebViewClient(){
    公共布尔shouldOverrideUrlLoading(web视图查看,字符串URL){
        //做你处理codeS在这里,它的网址是请求的URL
        //可能是你需要打开该网址,而不是重定向:
        如果(url.startsWith(电话:)){
            startActivity(新意图(Intent.ACTION_DIAL,Uri.parse(URL)));
        }否则,如果(url.startsWith(电子邮件地址:)){
            URL = url.replaceFirst(电子邮件地址:,);
            URL = url.trim();
            意图I =新的意图(Intent.ACTION_SEND);
            i.setType(纯/文)。putExtra(Intent.EXTRA_EMAIL,
                    新的String [] {URL});
            startActivity(ⅰ);

        }否则,如果(url.startsWith(全球环境展望)){
            尝试 {
            }赶上(例外五){
                的System.out.println(E);
            }

        }否则,如果(url.endsWith(PDF)){

            尝试 {

            }赶上(例外五){
                的System.out.println(E);
            }

        } 其他 {
            view.loadUrl(URL);
        }
        返回true;
        //那么它在默认情况下的动作没有处理
    }
});
 

解决方案

这可能是简单的:

 尝试
{
 意图int​​entUrl =新的意图(Intent.ACTION_VIEW);
 intentUrl.setDataAndType(URL,应用程序/ PDF格式);
 intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 myActivity.startActivity(intentUrl);
}
赶上(ActivityNotFoundException E)
{
 Toast.makeText(myActivity,没有PDF浏览器安装,Toast.LENGTH_LONG).show();
}
 

虽然我还没有尝试过这一点。

在我们的应用程序,我们下载PDF格式的应用程序文件系统,使它成为可读的,然后传递路径的意图打开一个PDF浏览应用程序(例如Acrobat Reader软件)。请注意,您也想还需要与清理这些下载的PDF!有关

在你的try块认沽

 新DownloadPDFTask()执行(URL);
 

DownloadPDFTask类:

 公共类DownloadPDFTask扩展的AsyncTask<字符串,太虚,整数GT;
{
    保护ProgressDialog mWorkingDialog; //进度对话框
    保护字符串mFileName; //下载的文件
    保护字符串mError; //错误

    @覆盖
    保护整数doInBackground(字符串...网址)
    {

     尝试
     {
      字节[]的DataBuffer =新的字节[4096];
          INT NREAD = 0;

          //设置本地文件名,URL的最后一部分
          的String [] strURLParts =网址[0] .split(/);
          如果(strURLParts.length大于0)
            mFileName = strURLParts [strURLParts.length  -  1];
          其他
                mFileName =REPORT.pdf;

          // URL下载并存储到strFileName

          //连接网址
      的java.net.URL urlReport =新的java.net.URL(网址[0]);
          URLConnection的urlConn = urlReport.openConnection();
          InputStream的streamInput = urlConn.getInputStream();
          的BufferedInputStream bufferedStreamInput =新的BufferedInputStream(streamInput);
          FileOutputStream中的OutputStream = myActivity.openFileOutput(mFileName,Context.MODE_WORLD_READABLE); //必须是世界可读的,以便外部的意图可以打开!
          而((NREAD = bufferedStreamInput.read(DataBuffer中))大于0)
                outputStream.write(DataBuffer中,0,NREAD);
          streamInput.close();
          outputStream.close();
      }
      赶上(例外五)
      {
       Log.e(对myApp,e.getMessage());
       mError = e.getMessage();
       返回(1);
      }

     回报(0);
    }

    // ------------------------------------------------ -------------------------
    // preExecute  -  UI线程设置
    // ------------------------------------------------ -------------------------

    @覆盖
    在preExecute保护无效()
    {
     //显示下载,请等待对话框
     mWorkingDialog = ProgressDialog.show(myActivity,,下载PDF文件,请稍候......,真正的);
     返回;
    }

    // ------------------------------------------------ -------------------------
    // PostExecute  -  UI线程完成
    // ------------------------------------------------ -------------------------

    @覆盖
    保护无效onPostExecute(整数结果)
    {
         如果(mWorkingDialog!= NULL)
      {
       mWorkingDialog.dismiss();
       mWorkingDialog = NULL;
      }

         开关(结果)
         {
         情况下0://网址

            //意向查看下载PDF
            开放的我们的uri = Uri.fromFile(myActivity.getFileStreamPath(mFileName));

            尝试
            {
                意图int​​entUrl =新的意图(Intent.ACTION_VIEW);
                intentUrl.setDataAndType(URI,应用程序/ PDF格式);
                intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                myActivity.startActivity(intentUrl);
            }
            赶上(ActivityNotFoundException E)
            {
                Toast.makeText(myActivity,没有PDF浏览器安装,Toast.LENGTH_LONG).show();
            }

            打破;

        案例1://错误

            Toast.makeText(myActivity,mError,Toast.LENGTH_LONG).show();
            打破;

        }

    }

}
 

任何提及myActivity必须与参考替换你的Activity类

I have this webview code and I want to make it possible to have the PDF files opened when a user clicks on a PDF link. Here is the code, can you tell me what I have to put inside the PDF area of this? I've tried many different ways and I cannot get the PDF to view at all. Thanks for the help.

webview.setWebViewClient ( new WebViewClient() {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // do your handling codes here, which url is the requested url
        // probably you need to open that url rather than redirect:
        if (url.startsWith("tel:")) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
        } else if (url.startsWith("mailto:")) {
            url = url.replaceFirst("mailto:", "");
            url = url.trim();
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL,
                    new String[]{url});
            startActivity(i);

        } else if (url.startsWith("geo:")) {
            try {
            } catch (Exception e) {
                System.out.println(e);
            }

        } else if (url.endsWith("pdf")) {

            try {

            } catch (Exception e) {
                System.out.println(e);
            }

        } else {
            view.loadUrl(url);
        }
        return true;
        // then it is not handled by default action
    }
});

解决方案

This could be as simple as:

try
{
 Intent intentUrl = new Intent(Intent.ACTION_VIEW);
 intentUrl.setDataAndType(url, "application/pdf");
 intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 myActivity.startActivity(intentUrl);
}
catch (ActivityNotFoundException e)
{
 Toast.makeText(myActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
}

though I've not tried this.

In our apps, we DOWNLOAD the PDF to the apps file system, make it world readable, then pass the path in an Intent to open a PDF viewing app (e.g. Acrobat Reader). Please note that you'd also need to also be concerned with cleaning up these downloaded PDF's!

in your try block put

new DownloadPDFTask().execute(url);

DownloadPDFTask class:

public class DownloadPDFTask extends AsyncTask<String, Void, Integer> 
{
    protected ProgressDialog mWorkingDialog;    // progress dialog
    protected String mFileName;         // downloaded file
    protected String mError;            // for errors

    @Override
    protected Integer doInBackground(String... urls)
    {

     try
     {
      byte[] dataBuffer = new byte[4096];
          int nRead = 0;

          // set local filename to last part of URL
          String[] strURLParts = urls[0].split("/");
          if (strURLParts.length > 0)
            mFileName = strURLParts[strURLParts.length - 1];
          else
                mFileName = "REPORT.pdf";

          // download URL and store to strFileName

          // connection to url
      java.net.URL urlReport = new java.net.URL(urls[0]);
          URLConnection urlConn = urlReport.openConnection();
          InputStream streamInput = urlConn.getInputStream();
          BufferedInputStream bufferedStreamInput = new BufferedInputStream(streamInput);
          FileOutputStream outputStream = myActivity.openFileOutput(mFileName,Context.MODE_WORLD_READABLE); // must be world readable so external Intent can open!
          while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0)
                outputStream.write(dataBuffer, 0, nRead);
          streamInput.close();
          outputStream.close();
      }
      catch (Exception e)
      {
       Log.e("myApp", e.getMessage());
       mError = e.getMessage();
       return (1);
      }

     return (0);
    }

    //-------------------------------------------------------------------------
    // PreExecute - UI thread setup
    //-------------------------------------------------------------------------

    @Override
    protected void onPreExecute()
    {
     // show "Downloading, Please Wait" dialog
     mWorkingDialog = ProgressDialog.show(myActivity, "", "Downloading PDF Document, Please Wait...", true);
     return;
    }

    //-------------------------------------------------------------------------
    // PostExecute - UI thread finish
    //-------------------------------------------------------------------------

    @Override
    protected void onPostExecute (Integer result)
    {
         if (mWorkingDialog != null)
      {
       mWorkingDialog.dismiss();
       mWorkingDialog = null;
      }

         switch (result)
         {
         case 0:                            // a URL

            // Intent to view download PDF
            Uri uri  = Uri.fromFile(myActivity.getFileStreamPath(mFileName));

            try
            {
                Intent intentUrl = new Intent(Intent.ACTION_VIEW);
                intentUrl.setDataAndType(uri, "application/pdf");
                intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                myActivity.startActivity(intentUrl);
            }
            catch (ActivityNotFoundException e)
            {
                Toast.makeText(myActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
            }

            break;

        case 1:                         // Error

            Toast.makeText(myActivity, mError, Toast.LENGTH_LONG).show();
            break;

        }

    }

}

any reference to "myActivity" must be replaced with a reference to your Activity class

这篇关于Android的 - 里面的WebView加载PDF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆