【问题标题】:Android Web View not able to view PDF From Amazon Service UrlAndroid Web View 无法从 Amazon Service Url 查看 PDF
【发布时间】:2014-02-06 13:18:39
【问题描述】:

我正在尝试通过调用亚马逊网址在 android webview 中显示 pdf 文件。但它只显示白屏。没有加载。

当我使用亚马逊以外的网址时,它会在 webview 中显示 pdf 文件。 我也试过这个: http://docs.google.com/gview?embedded=true&url=" + MYURL

我也尝试过 write url:并且效果很好。 http://www.durgasoft.com/Android%20Interview%20Questions.pdf

如果有人有任何建议,请指导我。

这是我的代码供您参考:

 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 ;

谢谢。

【问题讨论】:

  • 你能发布你的堆栈跟踪吗?
  • 它没有显示任何错误或警告。

标签: android pdf amazon-web-services webview


【解决方案1】:

要从亚马逊网络服务显示 PDF,您需要先下载 PDF 并将其存储到您的设备,然后通过您设备上可用的 PDF 阅读器/查看器应用程序打开它。

1>> 致电DownloadFileAsync() 调用下载过程并传递您的亚马逊网络服务网址。

new DownloadFileAsync().execute(url);

2>> 在 AsyncTask 中执行下载 PDF 过程。

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>>下载pdf后拨打showPdfFromSdCard()

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>> 在您的onResume() 中调用deletePdfFromSdcard()

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

【讨论】:

    【解决方案2】:

    您需要在应用程序标签之外的清单文件中添加互联网权限。

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

    【讨论】:

    • 如果您对此有任何其他想法,请帮助我。
    • 除非您有错误消息,或者堆栈跟踪中的错误,否则我无能为力...
    【解决方案3】:

    经过 2 天的研究没有找到解决方案,所以我尝试先从亚马逊网络服务下载 PDF 文件并存储到 SD 卡中,然后在我的代码中打开 PDF 文件

    注意:- 此解决方案仅适用于在 Amazon Web 服务的 Web 视图中显示 PDF。 从其他网络服务试试这个代码:-

       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);
    

    ----------------------------------------------- -----------------------------------------------------------> 对于亚马逊网络服务请试试这个代码

       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>> 从 SD 卡显示 PDF

    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();
        }
    

    下载 PDF 后调用 showPdfFromSdCard 方法。

    显示 PDF 后,您从 SD 卡中删除 PDF 文件 这里是从 SD 卡中删除 PDF 的代码

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

    【讨论】:

    • 我想在 webview 中打开下载的文件(位置是下载文件夹)。可能吗?如果是,请分享
    • 有没有不下载pdf预览s3 url的解决方案?
    【解决方案4】:
    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:
    

    请将此库添加到您的 gradle 文件中。 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"
        />
    

    第 3 步:

    PDFView pdfView;

    输入流输入流;

    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();
    }
    

    最后一步:致电new DownloadFileAsync().execute(url);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 2014-01-04
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      相关资源
      最近更新 更多