2016-11-28 71 views
1

我正在使用MuPDF庫在我的應用程序中顯示PDF .. 可以查看保存在內部或外部存儲器中的PDF,但如果應用程序存儲在應用程序的資產文件夾中,則不會顯示pdf。 。 如何在應用程序PDF中查看?如何從資產或原始文件夾查看pdf?

我見過的解決方案,說thatbwe可以在應用程序中的PDF文件的應用程序關聯的文件夾複製我們再後來就用它們...... ,但我不能讓那個..

這裏的代碼 -

public class MainActivity extends Activity { 

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

     Button showPDFBtn = (Button)findViewById(R.id.btn_show_pdf); 
     showPDFBtn.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 

     Uri uri = Uri.parse("file:///android_asset/test.pdf"); 
     Intent intent = new Intent(MainActivity.this, MuPDFActivity.class); 
     intent.setAction(Intent.ACTION_VIEW); 
     intent.setData(uri); 
     startActivity(intent); 



}} 
); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.menu_main, menu); 
     return true; 
    } 
} 
+1

確實可以將文件複製到內部存儲中,然後將其打開。你不知道該怎麼做? –

+1

參考http://stackoverflow.com/questions/6491210/how-to-open-a-pdf-stored-either-in-res-raw-or-assets-folder – sasikumar

+0

@VladMatvienko不,我是新來的android所以我無法克服這個......你能給出一個代碼示例嗎? – DarShan

回答

5

試試下面的代碼

private void readAssetAndMakeCopy() 
    { 
     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); 
     } 
    } 

確保包括

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

in manifest

+0

感謝man的幫助! –

+0

PLZ接受答案,並做upvote,如果上面的代碼可以幫助您 –

+0

抱歉的人忘了upvote。我不能接受這個答案,因爲問題不是我的。對不起 –

相關問題