2012-10-15 98 views
7

有沒有人有關於如何在Android中打開PDF文件的想法?我的代碼看起來這本:如何從資產文件夾中打開Android中的PDF文件?

public class SampleActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     CopyReadAssets();  
    } 

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

     InputStream in = null; 
     OutputStream out = null; 
     File file = new File(getFilesDir(), "git.pdf"); 
     try { 
      in = assetManager.open("git.pdf"); 
      out = 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.parse("file://" + getFilesDir() + "/git.pdf"), 
       "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

你可以看一下這個鏈接: http://stackoverflow.com/questions/6491210/how-to-open-a-pdf-stored-either-in-res-raw-or-assets-folder – omi0301

+0

看看這個的http:// stackoverflow.com/questions/6491210/how-to-open-a-pdf-stored-either-in-res-raw-or-assets-文件夾 – Aamirkhan

+0

@sai請指出我們面臨的問題,即任何異常/錯誤,或應用程序顯示可用的PDF查看器列表的列表? –

回答

2

下面是從資產的文件夾中打開PDF文件中的代碼,但你必須有你的設備上安裝PDF閱讀器:

private void CopyAssets() { 

     AssetManager assetManager = getAssets(); 

     InputStream in = null; 
     OutputStream out = null; 
     File file = new File(getFilesDir(), "fileName.pdf"); 
     try { 
      in = assetManager.open("fileName.pdf"); 
      out = 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.parse("file://" + getFilesDir() + "/fileName.pdf"), 
       "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); 
     } 
    } 
+3

這個答案本質上是從這一個逐字複製:http://stackoverflow.com/questions/17085574 /讀A-PDF文件 - 從資產文件夾 – csvan

相關問題