3
votes

I am trying to display pdf file in android webview by calling amazon url. But it only shows white screen.Nothing to load.

When i use url other then amazon it shows pdf file in webview. I have also tried this: http://docs.google.com/gview?embedded=true&url=" + MYURL

I have also tried under write url as well: And works well. http://www.durgasoft.com/Android%20Interview%20Questions.pdf

If any one have any suggestion please guide me.

Here is my code for your reference:

 webView.getSettings().setJavaScriptEnabled(true);
 webView.getSettings().setPluginState(PluginState.ON);
 String url = Common.getPdfFromAmazon("52f3761d290c4.pdf");   
 webView.loadUrl(url);

Android Menifest.xml also give Internet Permission:
**<uses-permission android:name="android.permission.INTERNET" />**

i can also try this "http://docs.google.com/gview?embedded=true&url=" + url ;

Here is my logcat image.

Thank you.

4
can you post your stacktrace ? - Hannoun Yassir
It doesn't shown any error or warning. - Dhaval Jivani

4 Answers

5
votes

For displaying a PDF from amazon web service you need to first download and store the PDF to your device and then open it through PDF reader/viewer application available on your device.

1>> Call DownloadFileAsync() to invoke download process and pass your amazon web service url.

new DownloadFileAsync().execute(url);

2>> Do the download PDF process in AsyncTask.

class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(final String... aurl) {

        try {
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File dir = new File(extStorageDirectory, "pdf");
            if(dir.exists()==false) {
                dir.mkdirs();
            }
            File directory = new File(dir, "original.pdf");
            try {
                if(!directory.exists())
                    directory.createNewFile();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            int lenghtOfFile = conexion.getContentLength();
            conexion.connect();
            conexion.setReadTimeout(10000);
            conexion.setConnectTimeout(15000); // millis

            FileOutputStream f = new FileOutputStream(directory);

            InputStream in = conexion.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
            }
            f.flush();
            f.close();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;

    }

    @Override
    protected void onPostExecute(String unused) {
    }
}

3>> Call showPdfFromSdCard() after downloading pdf.

public static  void showPdfFromSdCard(Context ctx) {
    File file = new File(Environment.getExternalStorageDirectory() + "/pdf/original.pdf");
    PackageManager packageManager = ctx.getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
        ctx.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(ctx,
                "No Application Available to View PDF",
                Toast.LENGTH_SHORT).show();
    }
}

4>> Call deletePdfFromSdcard() in your onResume()

public static void deletePdfFromSdcard(){
    File file = new    File(Environment.getExternalStorageDirectory()+"/pdf/original.pdf");
    boolean pdfDelete = file.delete();
}
2
votes

You need to add the internet permission to your manifest file outside of the application tag.

<uses-permission android:name="android.permission.INTERNET" /> 
1
votes

after 2 day research no solution find for that so i try to first download PDF file from Amazon web service and store into the SD-Card then open PDF File Here My Code

Note:- This solution is only try for Show PDF in Web view From Amazon web Service. from other web service try this Code:-

   WebView webview=(WebView)findviewbyid(R.id.Webview);
   String MyURL= "this is your PDF URL";
   String url = "http://docs.google.com/gview?embedded=true&url=" + MyURL;
   Log.i(TAG, "Opening PDF: " + url);
   webView.getSettings().setJavaScriptEnabled(true); 
   webView.loadUrl(url);

----------------------------------------------------------------------------------------------> For Amazon Web Service Please Try This code

   1>> Download PDF from Amazon WebService

public static void DownloadFile(String fileURL, File directory) {
    try {

        FileOutputStream f = new FileOutputStream(directory);
        URL u = new URL(fileURL);
        HttpURLConnection c = (HttpURLConnection) u.openConnection();
        c.setRequestMethod("GET");
        c.connect();

        InputStream in = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = in.read(buffer)) > 0) {
            f.write(buffer, 0, len1);
        }
        f.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

2>> Show PDF From SD-Card

public static  void showPdfFromSdCard(Context ctx)
{
    File file = new File(Environment.getExternalStorageDirectory()+"/pdf/MyPdf.pdf");
    PackageManager packageManager = ctx.getPackageManager();
    Intent testIntent = new Intent(Intent.ACTION_VIEW);
    testIntent.setType("application/pdf");
    List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    Uri uri = Uri.fromFile(file);
    intent.setDataAndType(uri, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
         ctx.startActivity(intent);
    } 
    catch (ActivityNotFoundException e) {
        Toast.makeText(ctx, 
            "No Application Available to View PDF", 
            Toast.LENGTH_SHORT).show();
    }

After Download PDF showPdfFromSdCard Method called.

After show PDF you Delete PDF file From SD-card Here Code for Delete PDF From SD-Card

public static void deletePdfFromSdcard(){
    File file = new    File(Environment.getExternalStorageDirectory()+"/pdf/MyPdf.pdf");
    boolean pdfDelete = file.delete();


}
0
votes
I will do some modification in @Monika Moon code,

if you don't want to save the File in the device, the process explained above is too long as well as required FileProvider to open the pdf in external pdf viewer.

so for the better solution please follow the below steps.
Step 1:

please add this library to your gradle file. AndroidPdfViewer

Step 2:

add this in your XML view->

   <com.github.barteksc.pdfviewer.PDFView
    android:id="@+id/pdfView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

Step 3:

PDFView pdfView;

InputStream inputStream;

pdfView=findViewById(R.id.pdfView);

        class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            if (mProgressDialog!=null)
            {
                Utils.cancelProgressDialog(mProgressDialog);
            }
            mProgressDialog = Utils.showProgressDialog(DocumentViewActivity.this);

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(final String... aurl) {

            try {

                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();
                conexion.setReadTimeout(20000);
                conexion.setConnectTimeout(25000); // millis


                 inputStream = conexion.getInputStream();

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;

        }

        @Override
        protected void onPostExecute(String unused) {


            if (inputStream != null) {
                pdfView.fromStream(inputStream)
                        .defaultPage(0)
                        .password(null)
                        .scrollHandle(null)
                        .enableAntialiasing(true)
                        .scrollHandle(new DefaultScrollHandle(DocumentViewActivity.this))
                        .spacing(0)
                        .onLoad(new OnLoadCompleteListener() {
                            @Override
                            public void loadComplete(int nbPages) {
                                Utils.cancelProgressDialog(mProgressDialog);

                            }
                        })
                        .load();
            }else {
                Utils.cancelProgressDialog(mProgressDialog);
            }
        }
    }
@Override
protected void onDestroy() {
    if (inputStream!=null)
    {
        try {
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    super.onDestroy();
}

Final Step : call new DownloadFileAsync().execute(url);