2016-11-28 70 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。我不能接受这个答案,因为问题不是我的。对不起 –

相关问题