Search code examples
androidmupdf

How to view pdf from assets or raw folder?


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

Solution

  • 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