2012-11-22 88 views
2

我正在寫一個應用程序,當你點擊一個按鈕時打開一個pdf文件。下面是我的代碼:如何從res/raw文件夾打開PDF文件?

File pdfFile = new File(
         "android.resource://com.dave.pdfviewer/" 
           + R.raw.userguide); 
       Uri path = Uri.fromFile(pdfFile); 
       Intent intent = new Intent(Intent.ACTION_VIEW); 
       intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       intent.setDataAndType(path, "application/pdf"); 

       startActivity(intent); 

然而,當我運行它,然後按它說的按鈕「的文件無法打開,因爲它不是有效的PDF文檔」。這讓我發瘋。我正確訪問文件嗎?有任何想法嗎?由於

+0

重複的問題在這裏找到:http://stackoverflow.com/questions/6491210/how-to-open-a-pdf-stored-either-in-res-raw-or-assets-folder –

回答

-1

您可以在Android上的文件夾資產插入您的PDF,然後嘗試使用:

File pdfFile = new File(getAsset().open("userguide.pdf")); 
       Uri path = Uri.fromFile(pdfFile); 
       Intent intent = new Intent(Intent.ACTION_VIEW); 
       intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       intent.setDataAndType(path, "application/pdf"); 

       startActivity(intent); 

編輯: 的URI從文件夾中的資產是:文件:/// android_asset/RELATIVE_PATH 然後來源將是:

File pdfFile = new File("file:///android_asset/userguide.pdf"); 
        Uri path = Uri.fromFile(pdfFile); 
        Intent intent = new Intent(Intent.ACTION_VIEW); 
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        intent.setDataAndType(path, "application/pdf"); 

        startActivity(intent); 
+1

File pdfFile = new File(getAsset()。open(「userguide.pdf」);不會編譯。它說構造函數File(InputStream)是undefined。 – DMC

+0

我編輯了我的答案,對不起 –

+0

現在它說文檔當我嘗試打開它時,路徑是無效的! – DMC

4

您必須將pdf從assets文件夾複製到sdcard文件夾。

..... 
copyFile(this.getAssets().open("userguide.pdf"), new FileOutputStream(new File(getFilesDir(), "yourPath/userguide.pdf"))); 

File pdfFile = new File(getFilesDir(), "yourPath/userguide.pdf"); Uri path = Uri.fromFile(pdfFile); 
        Intent intent = new Intent(Intent.ACTION_VIEW); 
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        intent.setDataAndType(path, "application/pdf"); 

        startActivity(intent); 


} 

private void copyFile(InputStream in, OutputStream out) throws IOException { 
     byte[] buffer = new byte[1024]; 
     int read; 
     while((read = in.read(buffer)) != -1){ 
      out.write(buffer, 0, read); 
     } 
    } 
+0

請務必嘗試一下! –