如何从资产或原始文件夹中查看pdf?

时间:2016-11-28 06:15:11

标签: android mupdf

我正在使用MuPDF库在我的应用中显示pdf .. 可以查看保存在内部或外部存储器中的PDF,但如果它们存储在应用程序的资源文件夹中,则应用程序不显示pdf ... 如何在应用PDF中查看?

我见过这样的解决方案,说我们可以在app相关文件夹中复制我们的应用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 个答案:

答案 0 :(得分: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" />
清单中的