Android WebView with PDF Download

I am loading a page inside a webview

webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.xxxxxxxxx/howtoguide.aspx");

      

then inside webview i have several functions to click event below

            @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url.contains("concierge@xxxx.com.sg")) {
                final Intent eIntent = new Intent(
                        android.content.Intent.ACTION_SEND);
                eIntent.setType("plain/text");
                eIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                        new String[]{"xxxxxx"});
                eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                        "");
                eIntent.putExtra(android.content.Intent.EXTRA_TEXT,
                        "Text to be send");
                startActivity(Intent.createChooser(eIntent,
                        "Send mail..."));

            } else if (url.startsWith("tel:")) {

            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);
                view.reload();

            } else if (url.contains(".pdf")) {
            //Intent intent = new Intent(Intent.ACTION_VIEW);
            //intent.setDataAndType(Uri.parse(url), "application/pdf");
            //try{
            //view.getContext().startActivity(intent);
            //} catch (ActivityNotFoundException e) {
            //user does not have a pdf viewer installed
            //}
            // view.loadUrl("https://docs.google.com/viewer?url=" + url);
               view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);               
            } else {
                view.loadUrl(url);
            }
            return true;
        }

      

this webview has a click event for PDF. So if I click on this, the PDF won't load

+3


source to share


3 answers


view.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + url);

      

This method call works for me when I called to load inside the webview. Therefore this web view layout height must be match_parent.

Click the link to open your browser and then just enter the URL as shown below.



 Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                startActivity(intent);

      

This solved my problem.

+1


source


Please check below example code for your requirement

private void init()
{
    WebView webview = (WebView) findViewById(R.id.webview);
    WebSettings settings = webview.getSettings();
    settings.setJavaScriptEnabled(true);
    webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

    MyWebViewClient webViewClient = new MyWebViewClient(this, webview);
    webViewClient.loadUrl(YOUR_URL);
}

private class MyWebViewClient extends WebViewClient
{
    private static final String TAG = "MyWebViewClient";
    private static final String PDF_EXTENSION = ".pdf";
    private static final String PDF_VIEWER_URL = "https://drive.google.com/viewerng/viewer?embedded=true&url=";

    private Context mContext;
    private WebView mWebView;
    private ProgressDialog mProgressDialog;
    private boolean isLoadingPdfUrl;

    public MyWebViewClient(Context context, WebView webView)
    {
        mContext = context;
        mWebView = webView;
        mWebView.setWebViewClient(this);
    }

    public void loadUrl(String url)
    {
        mWebView.stopLoading();

        if (!TextUtils.isEmpty(url))
        {
            isLoadingPdfUrl = isPdfUrl(url);
            if (isLoadingPdfUrl)
            {
                mWebView.clearHistory();
            }

            showProgressDialog();
        }

        mWebView.loadUrl(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url)
    {
        return shouldOverrideUrlLoading(url);
    }

    @SuppressWarnings("deprecation")
    @Override
    public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl)
    {
        handleError(errorCode, description.toString(), failingUrl);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
    {
        final Uri uri = request.getUrl();
        return shouldOverrideUrlLoading(webView, uri.toString());
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public void onReceivedError(final WebView webView, final WebResourceRequest request, final WebResourceError error)
    {
        final Uri uri = request.getUrl();
        handleError(error.getErrorCode(), error.getDescription().toString(), uri.toString());
    }

    @Override
    public void onPageFinished(final WebView view, final String url)
    {
        Log.i(TAG, "Finished loading. URL : " + url);
        dismissProgressDialog();
    }

    private boolean shouldOverrideUrlLoading(final String url)
    {
        Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);

        if (url.contains("concierge@xxxx.com.sg"))
        {
            Intent eIntent = new Intent(android.content.Intent.ACTION_SEND);
            eIntent.setType("plain/text");
            eIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"xxxxxx"});
            eIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
            eIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Text to be send");
            startActivity(Intent.createChooser(eIntent, "Send mail..."));
            return true;
        }
        else if (url.startsWith("tel:"))
        {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
            startActivity(intent);
            return true;
        }
        else if (!isLoadingPdfUrl && isPdfUrl(url))
        {
            mWebView.stopLoading();

            final String pdfUrl = PDF_VIEWER_URL + url;

            new Handler().postDelayed(new Runnable()
            {
                @Override
                public void run()
                {
                    loadUrl(pdfUrl);
                }
            }, 300);

            return true;
        }

        return false; // Load url in the webView itself
    }

    private void handleError(final int errorCode, final String description, final String failingUrl)
    {
        Log.e(TAG, "Error : " + errorCode + ", " + description + " URL : " + failingUrl);
    }

    private void showProgressDialog()
    {
        dismissProgressDialog();
        mProgressDialog = ProgressDialog.show(mContext, "", "Loading...");
    }

    private void dismissProgressDialog()
    {
        if (mProgressDialog != null && mProgressDialog.isShowing())
        {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    private boolean isPdfUrl(String url)
    {
        if (!TextUtils.isEmpty(url))
        {
            url = url.trim();
            int lastIndex = url.toLowerCase().lastIndexOf(PDF_EXTENSION);
            if (lastIndex != -1)
            {
                return url.substring(lastIndex).equalsIgnoreCase(PDF_EXTENSION);
            }
        }
        return false;
    }
}

      



Check out sample code to handle redirected urls and open PDF file without loading in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500

+1


source


You must be signed in to Google to use these methods.

Another way using pdf.js

You have to save the pdf file in SD card and upload as web.

Add pdfjs files to the Assets directory

 else if (url.contains(".pdf"))
        {
           File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

   view.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + file.getAbsolutePath() + "#zoom=page-width"); 
        }

      

Complete sample project

0


source







All Articles