Has anyone found a way to open or view a PDF file on Android? I understand that webview doesn't support PDF on android. I have PDF viewers on the handset, but how can I open the PDF from the app?
4 Answers
Accepted Answer
With some of the new APIs that have been exposed, this is now a lot easier. You don't need to hack anything in to the source code. Take a look at the following:
try { var f = Ti.Filesystem.getFile('your.pdf'); Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({ action: Ti.Android.ACTION_VIEW, type: 'application/pdf', data: f.getNativePath() })); } catch (err) { var alertDialog = Titanium.UI.createAlertDialog({ title: 'No PDF Viewer', message: 'We tried to open a PDF but failed. Do you want to search the marketplace for a PDF viewer?', buttonNames: ['Yes','No'], cancel: 1 }); alertDialog.show(); alertDialog.addEventListener('click', function(evt) { if (evt.index == 0) { Ti.Platform.openURL('http://search?q=pdf'); } }); }
Actually, I have a better answer now.
If you look at the source for what Titanium.Platform.openURL is doing on Android, you'll see it's creating and starting an intent. This works great for PDFs on most Android devices.
But it doesn't work exactly like it should, and I found it didn't work at all on a bunch of HTC android devices.
I got around this by pulling the source for Titanium Mobile down, and adding a new method to the Titanium.Platform: "openURLWithType". It looks something like this:
public boolean openURLWithType(String url, String type) { if (DBG) { Log.d(LCAT, "Launching viewer for: " + url); } Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW, uri); intent.setDataAndType(uri, type); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); try { getTiContext().getActivity().startActivity(intent); return true; } catch (ActivityNotFoundException e) { Log.e(LCAT,"Activity not found: " + url, e); } return false; }Two small differences: 1) intent.setDataAndType(uri, type) will let you specify what you're linking to so that third party apps can pick it up. 2) intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
Then I can do the following and the PDF is properly launched:
if (Ti.Platform.openURLWithType('my.pdf', 'application/pdf')) { // success! } else { alert('You need to download a PDF viewer from the market!'); }I'm working with the latest code from the 1.4x branch on github. I remember hearing rumor that they were adding support for this in 1.5 or something, but I don't know anything definite.
DM me @dawsontoth on Twitter if you want to know more about this approach...
you can simply open it using Google viewer http://docs.google.com/viewer?pli=1
I'm new to android and I'm trying to develop an application which creates the ".pdf" files i.e. i have one form(contains the information of the person) this information should be stored in the .pdf format.. so how to do this ???please help me out in this...
Your Answer
Think you can help? Login to answer this question!