简体   繁体   English

下载PDF文件

[英]Downloading a PDF file

In my application, the user needs to download PDF file from an url and store it on sdcard. 在我的应用程序中,用户需要从URL下载PDF文件并将其存储在sdcard上。 But the catch here is I can only use DefaultHttpClient to access the url. 但是这里的问题是我只能使用DefaultHttpClient来访问URL。 I found couple of solutions but none used DefaultHttpClient. 我找到了几种解决方案,但都没有使用DefaultHttpClient。 After downloading the PDF, I would also likie to view the PDF in my application. 下载PDF之后,我也希望在我的应用程序中查看PDF。

//use this method to download the pdf file //使用此方法下载pdf文件

 public void downloadPdfContent(String urlToDownload){

             try {

                 String fileName="xyz";
             String fileExtension=".pdf";

//           download pdf file.

                URL url = new URL(urlToDownload);
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
                String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
                File file = new File(PATH);
                file.mkdirs();
                File outputFile = new File(file, fileName+fileExtension);
                FileOutputStream fos = new FileOutputStream(outputFile);
                InputStream is = c.getInputStream();
                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);
                }
                fos.close();
                is.close();

               System.out.println("--pdf downloaded--ok--"+urlToDownload);
            } catch (Exception e) {
                e.printStackTrace();

            }
    }

// for viewing the pdf use this method //要查看pdf,请使用此方法

private void onPdfClick()
    {

//      String pdfFile = Environment.getExternalStorageDirectory()+ File.separator + AstroManager.file.getName();

         Intent intent = new Intent(Intent.ACTION_VIEW);
         intent.setDataAndType(Uri.fromFile(new File("/sdcard/mydownload/xyz.pdf"), "application/*");

         startActivity(intent);
    }

If you have to open pdf file, pdf reader must have to be installed in your device.Otherwise it will show blank screen. 如果必须打开pdf文件,则必须在设备中安装pdf阅读器,否则它将显示空白屏幕。 Also here is good example to download pdf from server and view its contents . 也是从服务器下载pdf查看其内容的好例子。

请参阅http://developer.android.com/reference/org/apache/http/client/methods/HttpGet.html ,以使用DefaultHttpClient从网址中检索数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM