2012-08-03 121 views
0

我創建了一個類openPDF,它將一個字節數組作爲輸入並用Adobe Reader顯示PDF文件。代碼:用Adobe Reader顯示PDF文件

private void openPDF(byte[] PDFByteArray) { 


    try { 
     // create temp file that will hold byte array 
     File tempPDF = File.createTempFile("temp", ".pdf", getCacheDir()); 
     tempPDF.deleteOnExit(); 

     FileOutputStream fos = new FileOutputStream(tempPDF); 
     fos.write(PDFByteArray); 
     fos.close(); 

     Intent intent = new Intent(); 
      intent.setAction(Intent.ACTION_VIEW); 
      Uri uri = Uri.fromFile(tempPDF); 
      intent.setDataAndType(uri, "application/pdf"); 
      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  

      startActivity(intent); 


    } catch (IOException ex) { 
     String s = ex.toString(); 
     ex.printStackTrace(); 
    } 
} 

當我經過打算,從Adobe Reader的錯誤是「無效的文件路徑」。我閱讀所有其他帖子有關下載和在Android中查看PDF,但力量幫助很大。有什麼建議麼?

+0

您是否嘗試過將非臨時文件作爲輸入到adobe應用程序? – 2012-09-26 11:37:08

回答

0

我做了這個代碼來打開現有Dowloads文件夾與Adobe公司的應用程序中的especific .pdf文件

File folder = new File(Environment.getExternalStorageDirectory(), "Download"); 
    File pdf = new File(folder, "Test.pdf"); 

    Uri uri = Uri.fromFile(pdf); 

    PackageManager pm = getPackageManager(); 
    Intent intent = pm.getLaunchIntentForPackage("com.adobe.reader"); 
    intent.setDataAndType(uri, "application/pdf"); 
    startActivity(intent); 

這對我的作品。所以我想你的問題可以是臨時文件。嘗試將文件寫入SD卡。爲此,您需要將android.permission.WRITE_EXTERNAL_STORAGE添加到您的AndroidManifest.xml中。

+1

工作完美..謝謝! – desidigitalnomad 2013-02-04 05:58:55

1

我認爲問題在於其他應用程序無法訪問應用程序專用數據區中的文件(如緩存目錄)。

候選方案:

  1. 改變文件的模式MODE_WORLD_READABLE,以便它可以通過其他應用

    ... 
    String fn = "temp.pdf"; 
    Context c = v.getContext(); 
    FileOutputStream fos = null; 
    try { 
        fos = c.openFileOutput(fn, Context.MODE_WORLD_READABLE); 
        fos.write(PDFByteArray); 
    } catch (FileNotFoundException e) { 
        // do something 
    } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
    } finally { 
        if (fos!=null) { 
         try { 
          fos.close(); 
         } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
         } 
        } 
    } 
    
    Intent intent = new Intent(); 
    intent.setAction(Intent.ACTION_VIEW); 
    String filename = c.getFilesDir() + File.separator + fn; 
    File file = new File(filename); 
    Uri uri = Uri.fromFile(file); 
    intent.setDataAndType(uri, "application/pdf"); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
    startActivity(intent); 
    ... 
    
  2. 或寫入PDF文件到/ SD卡分區讀取。

    您可以使用android.os.Environment API來獲取路徑,並記得將權限添加到您的應用的AndroidManifest.xml文件。

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

問候

紫藤陳

相關問題