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] :
Button read = (Button) findViewById(R.id.read);
// Press the button and Call Method => [ ReadPDF ]
read.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
ReadPDF();
}
});
}
private void ReadPDF()
{
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), "MyPdf.pdf"); //<= PDF file Name
try
{
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());
}
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() > 0 && file.isFile()) {
//Toast.makeText(MainActivity.this,"Pdf Reader Exist !",Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
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();
}
}
private void copypdf(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[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"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Read PDF !"
android:id="@+id/read"/>
</LinearLayout>
Step 4 : Permission :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
That's all :)
Good Luck !