Android - Load PDF inside webview

前端 未结 5 1095
暖寄归人
暖寄归人 2020-12-28 11:11

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

5条回答
  •  轮回少年
    2020-12-28 11:59

    I was trying to handle this exact same scenario. The solution I came up with is below.

    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                String cleanUrl = url;
                if (url.contains("?")) {
                    // remove the query string
                    cleanUrl = url.substring(0,url.indexOf("?"));
                }
    
                if (cleanUrl.endsWith("pdf")) {
    
                    try {
                        Uri uriUrl = Uri.parse(cleanUrl);
                        Intent intentUrl = new Intent(Intent.ACTION_VIEW, uriUrl);
                        startActivity(intentUrl);
                        return true;
    
                    } catch (Exception e) {
                        System.out.println(e);
                        Toast.makeText(context,"No PDF Viewer Installed", Toast.LENGTH_LONG).show();
                    }
                }
    
                return false;
            }
    

    I needed to make sure it would handle pdf links, even if there was a query string. Still a bit hacky as the cleanUrl needs to end in "pdf", but so long as that is true, this should work. If you're serving up pdf's through a php script or something, you might want to dig a little deeper, handle things based on MIME type or something.

提交回复
热议问题