Search code examples
javaandroidpdfwebviewwebviewclient

Android - Load PDF inside webview


I have this webview code and I want to make it possible to have the PDF files opened when a user clicks on a PDF link. Here is the code, can you tell me what I have to put inside the PDF area of this? I've tried many different ways and I cannot get the PDF to view at all. Thanks for the help.

webview.setWebViewClient ( new WebViewClient() {
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // do your handling codes here, which url is the requested url
        // probably you need to open that url rather than redirect:
        if (url.startsWith("tel:")) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
        } else if (url.startsWith("mailto:")) {
            url = url.replaceFirst("mailto:", "");
            url = url.trim();
            Intent i = new Intent(Intent.ACTION_SEND);
            i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL,
                    new String[]{url});
            startActivity(i);

        } else if (url.startsWith("geo:")) {
            try {
            } catch (Exception e) {
                System.out.println(e);
            }

        } else if (url.endsWith("pdf")) {

            try {

            } catch (Exception e) {
                System.out.println(e);
            }

        } else {
            view.loadUrl(url);
        }
        return true;
        // then it is not handled by default action
    }
});

Solution

  • This could be as simple as:

    try
    {
     Intent intentUrl = new Intent(Intent.ACTION_VIEW);
     intentUrl.setDataAndType(url, "application/pdf");
     intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
     myActivity.startActivity(intentUrl);
    }
    catch (ActivityNotFoundException e)
    {
     Toast.makeText(myActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
    }
    

    though I've not tried this.

    In our apps, we DOWNLOAD the PDF to the apps file system, make it world readable, then pass the path in an Intent to open a PDF viewing app (e.g. Acrobat Reader). Please note that you'd also need to also be concerned with cleaning up these downloaded PDF's!

    in your try block put

    new DownloadPDFTask().execute(url);
    

    DownloadPDFTask class:

    public class DownloadPDFTask extends AsyncTask<String, Void, Integer> 
    {
        protected ProgressDialog mWorkingDialog;    // progress dialog
        protected String mFileName;         // downloaded file
        protected String mError;            // for errors
    
        @Override
        protected Integer doInBackground(String... urls)
        {
    
         try
         {
          byte[] dataBuffer = new byte[4096];
              int nRead = 0;
    
              // set local filename to last part of URL
              String[] strURLParts = urls[0].split("/");
              if (strURLParts.length > 0)
                mFileName = strURLParts[strURLParts.length - 1];
              else
                    mFileName = "REPORT.pdf";
    
              // download URL and store to strFileName
    
              // connection to url
          java.net.URL urlReport = new java.net.URL(urls[0]);
              URLConnection urlConn = urlReport.openConnection();
              InputStream streamInput = urlConn.getInputStream();
              BufferedInputStream bufferedStreamInput = new BufferedInputStream(streamInput);
              FileOutputStream outputStream = myActivity.openFileOutput(mFileName,Context.MODE_WORLD_READABLE); // must be world readable so external Intent can open!
              while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0)
                    outputStream.write(dataBuffer, 0, nRead);
              streamInput.close();
              outputStream.close();
          }
          catch (Exception e)
          {
           Log.e("myApp", e.getMessage());
           mError = e.getMessage();
           return (1);
          }
    
         return (0);
        }
    
        //-------------------------------------------------------------------------
        // PreExecute - UI thread setup
        //-------------------------------------------------------------------------
    
        @Override
        protected void onPreExecute()
        {
         // show "Downloading, Please Wait" dialog
         mWorkingDialog = ProgressDialog.show(myActivity, "", "Downloading PDF Document, Please Wait...", true);
         return;
        }
    
        //-------------------------------------------------------------------------
        // PostExecute - UI thread finish
        //-------------------------------------------------------------------------
    
        @Override
        protected void onPostExecute (Integer result)
        {
             if (mWorkingDialog != null)
          {
           mWorkingDialog.dismiss();
           mWorkingDialog = null;
          }
    
             switch (result)
             {
             case 0:                            // a URL
    
                // Intent to view download PDF
                Uri uri  = Uri.fromFile(myActivity.getFileStreamPath(mFileName));
    
                try
                {
                    Intent intentUrl = new Intent(Intent.ACTION_VIEW);
                    intentUrl.setDataAndType(uri, "application/pdf");
                    intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    myActivity.startActivity(intentUrl);
                }
                catch (ActivityNotFoundException e)
                {
                    Toast.makeText(myActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
                }
    
                break;
    
            case 1:                         // Error
    
                Toast.makeText(myActivity, mError, Toast.LENGTH_LONG).show();
                break;
    
            }
    
        }
    
    }
    

    any reference to "myActivity" must be replaced with a reference to your Activity class