从android中的url加载pdf

时间:2016-05-19 15:32:04

标签: android pdf webview

我必须使用此链接在webview中显示pdf文件 https://col1.3yd.co:8087/api/getDoc?username=test&password=12345678&doc_id=dc_1

问题是,当我使用在线谷歌文档查看器在webview中打开此链接时,我收到错误“哎呀!!显示此图像时出现问题。”

https://docs.google.com/gview?embedded=true&url=https://col1.3yd.co:8087/api/getDoc?username=test&password=12345678&doc_id=dc_1

从stackoverflower尝试了太多方法后,我使用此代码加载pdf文件。 问题是每次下载文件及其花费时间。还有其他方法可以在webview中显示文件。

 private void downloadAndOpenPDF(){

 progressDialog = new DLProgressDialog(context);
            progressDialog.show();

    new Thread(new Runnable() {
        public void run() {


            Uri path = Uri.fromFile(downloadFile(download_file_url));
            try {
                if(progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(path, "application/pdf");
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);

            } catch (ActivityNotFoundException e) {

            }
        }
    }).start();

}

private File downloadFile(String dwnload_file_path) {
    File file = null;
    try {
        URL url = new URL(dwnload_file_path);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        // connect
        urlConnection.connect();
        // set the path where we want to save the file
        File SDCardRoot = Environment.getExternalStorageDirectory();
        // create a new file, to save the downloaded file
        file = new File(SDCardRoot, dest_file_path);
        FileOutputStream fileOutput = new FileOutputStream(file);
        // Stream used for reading the data from the internet
        InputStream inputStream = urlConnection.getInputStream();
        // this is the total size of the file which we are
        // downloading
        totalsize = urlConnection.getContentLength();
        // create a buffer...
        byte[] buffer = new byte[1024 * 1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
            downloadedSize += bufferLength;
            per = ((float) downloadedSize / totalsize) * 100;
              }
        // close the output stream when complete //
        fileOutput.close();

    } catch (final MalformedURLException e) {

    } catch (final IOException e) {

    } catch (final Exception e) {

    }
    return file;
}

0 个答案:

没有答案