I have a simple app with a webview. Every time there is a PDF link on a page, after clicking it nothing happens. I am currently strangling with pdf links, they wont open no matter what. I tried some solutions but they just seam outdated.
Here is my code :
package com.example.bla;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
private WebView webView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView=findViewById(R.id.webviewid);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setDomStorageEnabled(true);
webSettings.setPluginState(WebSettings.PluginState.ON);
webSettings.setAllowFileAccess(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://blabla.com");
}
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
Can you please help me with a solution?
When you click a link to a .PDF the webview will try to download the file. What you really want to do is open the file in an external browser session. That will display the PDF, and also give you the choice to download it if you wish. To do that, first set a download listener for your webview.
//for download PDF files
webView.setDownloadListener(new MyDownLoadListener());
Then, in the download listener, send the PDF link to an external browser session:
public class MyDownLoadListener implements DownloadListener {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
if (url != null) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With