androidandroid-layoutpdfandroid-intentandroid-listview

Android Reading PDF files from asstes folder


I have list of PDF files need to Place in asstes folder,my requirement is to read files from asstes and display it inside a listview. if we click on each list item need to read respective PDF file

I have followed this blog http://androidcodeexamples.blogspot.in/2013/03/how-to-read-pdf-files-in-android.html

But here they have given reading a PDF files from External Storage Directory

I want to implement the same reading files from Asstes Folder

Could any one help How to implement the same example reading files from asstes?


Solution

  • You cannot open the pdf file directly from the assets folder.You first have to write the file to sd card from assets folder and then read it from sd card.

    Try out the below code to copy and read the file from assets folder:

     //method to write the PDFs file to sd card 
     private void PDFFileCopyandReadAssets()
        {
            AssetManager assetManager = getAssets();
    
            InputStream in = null;
            OutputStream out = null;
            File file = new File(getFilesDir(), "test.pdf");
            try
            {
                in = assetManager.open("test.pdf");
                out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
    
                readFile(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() + "/test.pdf"),
                    "application/pdf");
    
            startActivity(intent);
        }
    
        private void readFile(InputStream in, OutputStream out) throws IOException
        {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, read);
            }
        }
    

    Open the file from sdcard as below:

    File file = new File("/sdcard/test.pdf");        
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file),"application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);
    

    Also provide a permission to write into your external storage in your manifest.

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