How to view pdf from assets or raw folder?

六月ゝ 毕业季﹏ 提交于 2019-12-24 07:07:02

问题


I am using the MuPDF library to display pdf in my app.. It is possible to view PDFs saved in internal or external memories but the App doesn't show the pdf if they are stored in assets folder of the app... How to view in app PDFs?

I've seen solutions which say thatbwe can copy our in app PDFs in app associated folder and then use them later on... but I can't get that..

here's the code -

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:


Try below code

 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);
        }
    }

Make sure to include

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

in manifest



来源:https://stackoverflow.com/questions/40838153/how-to-view-pdf-from-assets-or-raw-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!