How to view or download any PDF file in Webview?

Asked

Viewed 1,880 times

3

I tried to find some solutions to the problem. But there are only codes that download a specific file.

I have a website that opens in a webview. On the page there are several Pdfs. I need a code that downloads or displays the files.

Follow the code I’m using for webview:

public class Environmentaula extends Activity {

private WebView webViewAmbienteAula1;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_ambiente_aula);

    String url = "http://www.meusite.com";
    WebView view = (WebView)
            this.findViewById(R.id.webViewAmbienteAula);
    view.setWebViewClient(new WebViewClient());

    view.getSettings().setJavaScriptEnabled(true);
    view.loadUrl(url);


}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
    WebView view = (WebView)
            this.findViewById(R.id.webViewAmbienteAula);
    if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()){
        view.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);


}

}

  • I already did, but I don’t remember. I know the webview itself has an event. http://stackoverflow.com/questions/10069050/download-file-inside-webview

1 answer

2

Use the setDownloadListener.

mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
        String contentDisposition, String mimetype,
        long contentLength) {
            Request request = new Request( Uri.parse(url));
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myPDFfile.pdf"); 
            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            dm.enqueue(request);        
     }
 });

Behold here a nice implementation, I hope it helps you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.