2014-01-30 54 views
0

我開發的,我想顯示從資產PDF文件的應用程序顯示出來。我做了這麼多谷歌,也試過一些排列組合,但沒有工作。的Android - 閱讀PDF和使用意圖

CODE:

private void CopyReadAssets() 
{ 
    AssetManager assetManager = getActivity().getAssets(); 

    InputStream in = null; 
    OutputStream out = null; 
    File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc.pdf"); 
    try 
    { 
     in = assetManager.open("abc.pdf"); 
     out = getActivity().openFileOutput(file.getName(), Context.MODE_WORLD_READABLE); 

     copyFile(in, out); 
     in.close(); 
     in = null; 
     out.flush(); 
     out.close(); 
     out = null; 
    } 
    catch (Exception e) 
    { 
     Log.e("tag", e.getMessage()); 
    } 

    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.fromFile(file), "application/pdf"); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
    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); 
    } 
} 

當我點擊列表中,我稱之爲CopyReadAssets()函數,那麼它會提示我在瀏覽器,您要打開,然後我就AdobeReader點擊則顯示以下錯誤。

回答

5

我檢查你的代碼有一些錯誤,你必須改變,可能是你從here.

複製的代碼

替換 AssetManager assetManager = getAssets();

而不是AssetManager assetManager = getActivity().getAssets();

直接使用File file = new File(getFilesDir(), "abc.pdf");

而不是

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc.pdf");

希望它爲你工作。!

+0

我試圖getFilesDir()...仍然是相同的錯誤 –

+0

而我必須使用getActivity.getAssets()..因爲我在片段 –

+0

把這兩個函數在try catch塊,讓我知道你得到哪個錯誤, –

1

爲此,您可以通過使用Web視圖 -

 webview = (WebView) findViewById(R.id.prayertimes_webview); 
    webview.getSettings().setJavaScriptEnabled(true); 
    webview.getSettings().setPluginsEnabled(true); 
    webview.getSettings().setSupportZoom(true); 
    webview.getSettings().setBuiltInZoomControls(true); 
      String urll = "http://docs.google.com/gview?embedded=true&url=" + url; 
      webview.setWebViewClient(new WebViewClient()); 
      webview.loadUrl(urll); 
+0

網址???????????? –

+0

這是你想要打開的pdf的網址.. –

+0

你可以通過將它作爲docs.google.com/gview?embedded=true&url=發送到谷歌並將你的pdf文件傳給你來打開你的pdf。 –

0

的PDF文件無法從PDF閱讀器看到的,因爲你的資產裏的任何東西都是私人應用程式。你必須以某種方式公開它。這有幾種方法。

最複雜的方法是實施公開ContentProvider並覆蓋其中的openAssetFile方法。通過該文件的URL通過Intent和PDF閱讀器應該能夠使用ContentResolveropenAssetFileDescriptor方法得到的PDF文件。

這是鏈接。 - http://www.nowherenearithaca.com/2012/03/too-easy-using-contentprovider-to-send.html