Displaying PDF file with Adobe Reader - android

I created a class openPDF which takes a byte array as input and displays the PDF file with Adobe Reader. Code:
private void openPDF(byte[] PDFByteArray) {
try {
// create temp file that will hold byte array
File tempPDF = File.createTempFile("temp", ".pdf", getCacheDir());
tempPDF.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempPDF);
fos.write(PDFByteArray);
fos.close();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(tempPDF);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (IOException ex) {
String s = ex.toString();
ex.printStackTrace();
}
}
When I pass the intend , the error from adobe reader is "Invalid file path". I read all other posts related to downloading and viewing PDF in android but dint help much. Any suggestions?

I think the issue is that other apps have no access to the files in your app's private data area (like the cache dir).
Candidate solutions:
changing the file's mode to MODE_WORLD_READABLE so that it can be read by other apps
...
String fn = "temp.pdf";
Context c = v.getContext();
FileOutputStream fos = null;
try {
fos = c.openFileOutput(fn, Context.MODE_WORLD_READABLE);
fos.write(PDFByteArray);
} catch (FileNotFoundException e) {
// do something
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fos!=null) {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
String filename = c.getFilesDir() + File.separator + fn;
File file = new File(filename);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
...
or write the pdf file to the /sdcard partition.
you can use android.os.Environment API to get the path, and remember to add the permission to your app's AndroidManifest.xml file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Regards
Ziteng Chen

I made this code to open an especific .pdf file existing in Dowloads folder with Adobe's application
File folder = new File(Environment.getExternalStorageDirectory(), "Download");
File pdf = new File(folder, "Test.pdf");
Uri uri = Uri.fromFile(pdf);
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.adobe.reader");
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
It works for me. So i guess your problem can be the temprorary file. Try to write the file to sdcard. To do this you will need add android.permission.WRITE_EXTERNAL_STORAGE to your AndroidManifest.xml.

Related

Android intent opens blank PDF even though I used the same path used for saving it

I'm trying to generate a PDF from a layout with:
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(2480, 3508, 0).create();
PdfDocument.Page page = document.startPage(pageInfo);
linearview.draw(page.getCanvas());
document.finishPage(page);
OutputStream outStream;
File file = new File(getExternalFilesDir(null), "pedido.PDF");
try {
outStream = new FileOutputStream(file);
document.writeTo(outStream);
document.close();
outStream.flush();
outStream.close();
Log.d(TAG, "pdf saved to " + getExternalFilesDir(null));
Intent intent = new Intent(Intent.ACTION_VIEW);
File myPDF = new File(getExternalFilesDir(null), "pedido.PDF");
Uri uri = FileProvider.getUriForFile(OrderActivity.this, BuildConfig.APPLICATION_ID + ".provider", myPDF);
Log.d(TAG, "openPDF: intent with uri: " + uri);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d(TAG, e.toString());
}
When I run this code, I get a blank PDF opened by the defaut PDF opener. I don't know if it does that because it didn't find the PDF file, but I guess it's the problem, because the PDF is generated correctly. If I go with a file searcher and open the file /storage/emulated/0/Android/data/com.lucaszanella.venko/files/pedido.PDF I see the PDF normally.
This is the output I get
D/OrderActivity: pdf saved to /storage/emulated/0/Android/data/com.lucaszanella.venko/files
D/OrderActivity: openPDF: intent with uri: content://com.lucaszanella.venko.provider/external_files/Android/data/com.lucaszanella.venko/files/pedido.PDF
As you can see, the pdf is saved to the /storage folder, but the intent tries to open from /external_files. This migth be the problem, but I did everything alrigth, I guess.
Update:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external_files"
path="." />
</paths>
this is what was missing:
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
even though I don't need permissions to read from the external directory.
Try
Uri uri = Uri.fromFile(myPDF);
instead of
Uri uri = FileProvider.getUriForFile(OrderActivity.this, BuildConfig.APPLICATION_ID + ".provider", myPDF);

Getting the file if openFileOutput is used

I am saving my file to app's private internal storage like this then I pass that file into a Uri so I can return it as a result in my other activity
String filename = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(data);
outputStream.close();
Intent intent = new Intent();
intent.setData(Uri.fromFile("")); //pass file here somehow
setResult(Activity.RESULT_OK);
finish();
} catch (IOException e) {
Toast.makeText(CameraActivity.this, "Error creating file " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
How do you get the File from openFileOutput ?
How do you get the File from openFileOutput ?
Use Context.getFilesDir() for getting file path which is created using openFileOutput method:
String rootDir = this.getFilesDir().getAbsolutePath();
File file = new File(rootDir + filename);
.....
intent.setData(Uri.fromFile(file));
I made this solution for the very same problem, I like this one better:
Uri internalFilesUri = Uri.fromFile(getContext().getFilesDir());
Uri fileUri = Uri.withAppendedPath(internalFilesUri , filename);

create and open a sample pdf file while inside the application

I want to open a pdf file when inside the application(internal storage).I have the following code.But once adobe pdf is opened it shows a pop up error as " The document path is not valid".Is it not possible to only read a pdf file from inside the app? If not please let me know how can I copy it to the external storage.Thanks in advance
File file_source = new File(getApplicationContext().getFilesDir()+"/"+"sample.pdf");
String string = "Hello world!";
try
{
file_source.createNewFile();
FileOutputStream outputStream;
outputStream = openFileOutput("sample.pdf", Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
if(file_source.exists())
{
Uri path = Uri.fromFile(file_source);
Intent intent1 = new Intent(Intent.ACTION_VIEW);
intent1.setDataAndType(path, "application/pdf");
intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent1);
}
catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
Intent intent2 = new Intent(Intent.ACTION_VIEW);
startActivity(intent2);
}
}
else
{
Log.d("TAG","no file exists");
}
}
catch (FileNotFoundException e) {
Log.d("TAG","File not found");
}
catch (IOException ioe) {
Log.d("TAG","Exception while reading file" + ioe);
}
Files in the internal storage directory of your app are by default private to your application. Which means that no PDF-Reader app can read that file (since it doesn't run with your apps pid - no read permission is given).
You have to save that PDF with explicit reading permissions for other apps by using the Context.MODE_WORLD_READABLE flag.
Also use Context.openFileOutput() and Context.openFileInput() to read and write files in your internal directory . Don't hardcode paths like this, they might change.
You can copy the file from internal storage to external storage by below code.
try {
String file_name="inputpdf.pdf";
File tempfile = new File(directory, file_name);
FileInputStream inStream = new FileInputStream(tempfile);
//where ctx is your context (this)
FileOutputStream fos = ctx.openFileOutput("Outputpdf", ctx.MODE_WORLD_WRITEABLE|ctx.MODE_WORLD_READABLE);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
fos.write(buffer, 0, length);
}
inStream.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}

Android open PDF : File not found

I try to open a PDF in my application.
First, I create the PDF like that :
String filename = Environment.getExternalStorageDirectory().toString()+"/mypdf.pdf";
File file = new File(filename);
try {
FileOutputStream bos = new FileOutputStream(file);
bos.write(Base64.decode(base64, 0));
bos.flush();
bos.close();
} catch (IOException e) {
Log.e(TAG, "IOError with PDF");
e.printStackTrace();
}
Intent intent = new Intent(this, PdfActivity.class);
intent.putExtra("file", filename);
startActivity(intent);
The file is well created and readable, I can open this with ESExplorer application.
This file is located in /storage/emulated/0/myfile.pdf
in the PdfActivity I try to open the PDF :
Bundle extras = getIntent().getExtras();
String url = extras.getString("file");
File file = new File(url);
try {
if (file.exists()) {
Uri path = Uri.parse(url);
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(objIntent);
} else {
Toast.makeText(this, "File NotFound", Toast.LENGTH_SHORT).show();
}
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "No Viewer Application Found", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
file.exists() return true, Intent start, but my PDF reader says : "File not found"
I've added read and write permissions on external storage.
Does someone have any idea why it can't access to my file ?
objIntent.setDataAndType(url, "application/pdf");
use above line in your second snippest also declare String url as a global variable hope it will help you if it will not work try to use hardcode value of file path and see is it working or not ?
and are you sure file is exist? check this scenario tooo :)
I found the solution.
I've replace the Uri like that:
Uri path = Uri.fromFile(file);
And it works!

Android assest folder image attachment to email failed

I'm trying to send a mail attaching assest folder image to the mail, mail is sent successfully, but when i checked it there was no image attached to the mail,
this is my code,
Uri uri = Uri.fromFile(new File("file:///android_asset/Hat_5.png"));
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType("image/png");
intent.putExtra(Intent.EXTRA_EMAIL , new String[] { "some#gmail.com"});
intent.putExtra(Intent.EXTRA_SUBJECT, "New Order");
intent.putExtra(Intent.EXTRA_TEXT , "Order Id :" +imageId);
intent.putExtra(Intent.EXTRA_STREAM , uri);
startActivity(Intent.createChooser(intent, "Send mail..."));
permission,
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You can only attach files from the SDCARD.
You'll need to copy the image to the SDCARD and change the URI the the file's path on the sdcard.
You could delete if afterwards.
You can do this if you want
String FILENAME = "avatar.png";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
Log.v("","FileNotFoundException: "+e1.getMessage());
}
try {
InputStream inputStream = getAssets().open("avatar.jpg");
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0)
fos.write(buf,0,len);
fos.close();
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
Log.v("","IOException: "+e1.getMessage());
}
// Get the file from internal storage
String filePath = getApplicationContext().getFilesDir().getAbsolutePath();//returns current directory.
File file = new File(filePath, FILENAME);
then
Uri uri = Uri.fromFile(file);
intent.putExtra(Intent.EXTRA_STREAM , uri);
And send the attachment...

Categories

Resources