Search code examples
javaandroidwebviewandroid-webviewwebviewclient

android webview not loading/opening pdf


My webview is loading google chrome. When the user browses the webview app he can navigate to any links which is working fine. But when the user navigates to a link which contains pdf my webview fails to open or download the file. How can I achieve it?

public class WebViewPage extends AppCompatActivity {
WebView webView;
Button closeweb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_web_view_page);

    webView =findViewById(R.id.webview);
    closeweb = findViewById(R.id.closeweb);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);


     webView.setWebViewClient(new WebViewClient());

    webView.loadUrl("https://www.google.in");
     closeweb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(WebViewPage.this, HomePage.class);
            startActivity(intent);
        }
    });

}
@Override
public void onBackPressed() {

}

} enter image description here


Solution

  • Or perhaps if you want to open the PDF or any other format like XLSX or etc... you can use this:

    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        webView.loadUrl(url);
        if (url.endsWith(".pdf") || url.endsWith(".xlsx") || url.endsWith(".xls") || url.endsWith(".doc") || url.endsWith(".docx") || url.endsWith(".ppt") || url.endsWith(".pptx")) {
            webView.loadUrl("https://docs.google.com/gview?embedded=true&url=" + url);
           
            return true;
        }
        return false;
    }
    

    This will use the services of google for opening any type of files(supported by google docs).