Hi everyone, I have some code that I got from http://developer.appcelerator.com/blog/2011/09/sharing-project-assets-with-android-intents.html to view pdf's in Android.
Right now, it makes you push a button to view the pdf. Is there a way to make it automatically load the pdf without the use of the button? Here's the code I'm using.
Ti.UI.setBackgroundColor('#222'); var win = Ti.UI.createWindow({ navBarHidden: true, exitOnClose: true }); var button = Ti.UI.createButton({ title: 'open pdf', height: '60dp', width: '120dp', top: '140dp' }); var appFilePath = '12ALTAAGENG.pdf'; var appFile = Ti.Filesystem.getFile(appFilePath); var tmpFile = undefined, newPath = undefined; if (Ti.Filesystem.isExternalStoragePresent()) { tmpFile = Ti.Filesystem.createTempFile(); newPath = tmpFile.nativePath + '.pdf'; tmpFile.move(newPath); tmpFile = Ti.Filesystem.getFile(newPath); tmpFile.write(appFile.read()); } else { Ti.API.error('No external storage present'); } button.addEventListener('click', function(e) { if (tmpFile) { var intent = Ti.Android.createIntent({ action: Ti.Android.ACTION_VIEW, type: "application/pdf", data: tmpFile.nativePath }); try { Ti.Android.currentActivity.startActivity(intent); } catch(e) { Ti.API.debug(e); alert('No apps PDF apps installed!'); } } }); win.addEventListener('close', function(e) { tmpFile.deleteFile(); }); win.add(button); win.open();Thanks.
2 Answers
Try openStream( Number mode, String path )
http://docs.appcelerator.com/titanium/2.0/#!/api/Titanium.Filesystem-method-openStream
I seem to have figured it out. Combining the code from the link above and some code I was using before, I came up with this.
var appFilePath = '12ALTAAGENG.pdf'; var appFile = Ti.Filesystem.getFile(appFilePath); var tmpFile = undefined, newPath = undefined; if (Ti.Filesystem.isExternalStoragePresent()) { tmpFile = Ti.Filesystem.createTempFile(); newPath = tmpFile.nativePath + '.pdf'; tmpFile.move(newPath); tmpFile = Ti.Filesystem.getFile(newPath); tmpFile.write(appFile.read()); } else { Ti.API.error('No external storage present'); } try { var f = Ti.Filesystem.getFile(tmpFile); Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({ action: Ti.Android.ACTION_VIEW, type: 'application/pdf', data: tmpFile.nativePath })); } 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'); } }); }It's working the way I want it, but if anyone has a more efficient way to code this, I'm all ears.
Your Answer
Think you can help? Login to answer this question!