Reputation: 21
Trying to open pdf file from asset folder on clicking the button
public class CodSecreen extends AppCompatActivity {
PDFView pdfView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cod_secreen);
pdfView=(PDFView)findViewById(R.id.pdf);
Intent intent = getIntent();
String str = intent.getStringExtra("message");
if (str.equals(getResources().getString(R.string.introduction))){
pdfView.fromAsset("phpvariable.pdf").load();
}
}
}
by passing the string value of button
bttn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = bttn1.getText().toString();
Intent i=new Intent(DetailSecreen.this,CodSecreen.class);
startActivity(i);
}
});
Upvotes: 2
Views: 8421
Reputation: 2819
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:
fun openPdf(){
// Open the PDF file from raw folder
val 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 size
var read: Int
while (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 FileProvider
val uri = FileProvider.getUriForFile(this, "$packageName.provider", cacheFile)
if (uri != null) {
// Create an intent to open the PDF in a third party app
val 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-path
name="cache-files"
path="/" />
</paths>
Add the file provider configuration in your AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android: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.
Upvotes: 5
Reputation: 406
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 !
Upvotes: 2