Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 379
Abm Avatar asked Oct 19 '25 03:10

Abm


2 Answers

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).

like image 170
Sambhav Khandelwal Avatar answered Oct 20 '25 17:10

Sambhav Khandelwal


This is working for me and I am able to achieve opening of pdf

@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")) {
        activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
       
        return true;
    }
    return false;
}
like image 25
Abm Avatar answered Oct 20 '25 17:10

Abm