Skip to content Skip to sidebar Skip to footer

How To Open Pdf File From Assets Folder

Trying to open pdf file from asset folder on clicking the button public class CodSecreen extends AppCompatActivity { PDFView pdfView; @Override protected void onCreate

Solution 1:

You can do this in Four steps ☺

Step 1 : Create assets folder in your project and Place the PDF in it

:: For example : assets/MyPdf.pdf

Step 2 : Place the following code in your class [onCreate] :

Buttonread= (Button) findViewById(R.id.read);


// Press the button and Call Method => [ ReadPDF ]
read.setOnClickListener(newOnClickListener() {
       publicvoidonClick(View view) {
            ReadPDF();
    }
    });
    }
    privatevoidReadPDF()
    {
        AssetManagerassetManager= getAssets();
        InputStreamin=null;
        OutputStreamout=null;
        Filefile=newFile(getFilesDir(), "MyPdf.pdf"); //<= PDF file Nametry
        {
            in = assetManager.open("MyPdf.pdf"); //<= PDF file Name
            out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
            copypdf(in, out);
            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;
        } catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
        PackageManagerpackageManager= getPackageManager();
        IntenttestIntent=newIntent(Intent.ACTION_VIEW);
        testIntent.setType("application/pdf");
        Listlist= packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
        if (list.size() > 0 && file.isFile()) {
            //Toast.makeText(MainActivity.this,"Pdf Reader Exist !",Toast.LENGTH_SHORT).show();Intentintent=newIntent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(
                Uri.parse("file://" + getFilesDir() + "/MyPdf.pdf"),
                "application/pdf");
            startActivity(intent);
            }
            else {
            // show toast when => The PDF Reader is not installed !
            Toast.makeText(MainActivity.this,"Pdf Reader NOT Exist !",Toast.LENGTH_SHORT).show();
            }
        }
        privatevoidcopypdf(InputStream in, OutputStream out)throws IOException {
        byte[] buffer = newbyte[1024];
        int read;
        while ((read = in.read(buffer)) != -1)
        {
            out.write(buffer, 0, read);
        }
    }
}

Step 3 : Place the following code in your Layout :

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"><Buttonandroid:layout_height="wrap_content"android:layout_width="wrap_content"android:text="Read PDF !"android:id="@+id/read"/></LinearLayout>

Step 4 : Permission :

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

That's all :)

Good Luck !

Solution 2:

Android Q update

This is an older question, but with Android Q there are some changes because of the new file access permission/system. Now it's not possible anymore to just store the PDF file in a public folder. I solved this problem by creating a copy of the PDF file in the cache folder in data/data of my app. Whit this approach the permission WRITE_EXTERNAL_STORAGE is no longer required.

Open the PDF file:

funopenPdf(){
    // Open the PDF file from raw folderval inputStream = resources.openRawResource(R.raw.mypdf)

    // Copy the file to the cache folder
    inputStream.use { inputStream ->
        val file = File(cacheDir, "mypdf.pdf")
        FileOutputStream(file).use { output ->
            val buffer = ByteArray(4 * 1024) // or other buffer sizevar read: Intwhile (inputStream.read(buffer).also { read = it } != -1) {
                output.write(buffer, 0, read)
            }
            output.flush()
        }
    }

    val cacheFile = File(cacheDir, "mypdf.pdf")

    // Get the URI of the cache file from the FileProviderval uri = FileProvider.getUriForFile(this, "$packageName.provider", cacheFile)
    if (uri != null) {
        // Create an intent to open the PDF in a third party appval pdfViewIntent = Intent(Intent.ACTION_VIEW)
        pdfViewIntent.data = uri
        pdfViewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        startActivity(Intent.createChooser(pdfViewIntent, "Choos PDF viewer"))
    }
}

Provider configuration inside provider_paths.xml for accessing the file outside of your own app. This allows access to all files in the cache folder:

<?xml version="1.0" encoding="utf-8"?><paths><cache-pathname="cache-files"path="/" /></paths>

Add the file provider configuration in your AndroidManifest.xml

<providerandroid:name="androidx.core.content.FileProvider"android:authorities="${applicationId}.provider"android:exported="false"android:grantUriPermissions="true"><meta-dataandroid:name="android.support.FILE_PROVIDER_PATHS"android:resource="@xml/provider_paths" /></provider>

This could be enhanced by copying the files only once and checking if the file already exists and replacing it. Since opening PDFs is not a big part of my app I just keep it in the cache folder and override it every time the user opens the PDF.

Post a Comment for "How To Open Pdf File From Assets Folder"