如何从Android中的本地URL加载PDF文件

时间:2019-04-22 09:10:40

标签: android android-studio kotlin

我正在使用WebView加载PDF。

这是我来自本地网址的pdf文件:

String pdf = "http://192.168.1.181:8081/reports/RepoActivityLog181.pdf";

我的代码:

webView=new WebView(MainActivity.this);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);

        webView.setWebViewClient(new Callback());

        String pdfURL = "http://192.168.1.181:8081/reports/RepoActivityLog181.pdf";
        webView.loadUrl("http://docs.google.com/gview?embedded=true&url=" + pdfURL);

        setContentView(webView);
    }

    private class Callback extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(
                WebView view, String url) {
            return(false);
        }

,输出为: 无法预览

2 个答案:

答案 0 :(得分:0)

尝试一下:

字符串pdf =“ http://192.168.1.181:8081/reports/RepoActivityLog181.pdf”;

  Thorough Intent:

   Uri path = Uri.fromFile(pdf);
  Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
  pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  pdfOpenintent.setDataAndType(path, "application/pdf");
  try {
  startActivity(pdfOpenintent);
  }
  catch (ActivityNotFoundException e) {

  }

或Webview

   WebView webView = (WebView) findViewById(R.id.my_webview);
   webView.setWebViewClient(new MyWebViewClient());
   webView.addView(webView.getZoomControls());
   webView.getSettings().setJavaScriptEnabled(true);
   webView.loadUrl("http://docs.google.com/gview? 
  embedded=true&url="+pdf);

答案 1 :(得分:0)

在网络视图客户端方法shouldOverrideUrlLoading中,加载网址并返回true。

view.loadUrl(url);
return true;

还重写WebViewClient的onPageStarted方法以查看url是否为空...

 public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);

        if(url == null || url.equals(""))
            view.loadUrl("yoururl");

    }