Skip to content

Instantly share code, notes, and snippets.

@lbrenman
Last active June 3, 2020 01:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lbrenman/17edd67d5a4385772d0e to your computer and use it in GitHub Desktop.
Save lbrenman/17edd67d5a4385772d0e to your computer and use it in GitHub Desktop.
Appcelerator Titanium PDF Viewer Demo 1 - If not already loaded, then retrieve PDF from web site and store in file system and view

#PDF Viewer demo - from web site URL

  1. check if PDF has been downloaded from web site and stored in file system
  2. if not, then retrieve from web site and store in file system and open
  • use docviewer on ios and exernal app (via intent) on android
  1. if so, then open pdf
  • use docviewer on ios and exernal app (via intent) on android

Note that Android, the file is stored in the externalStorageDirectory (SDCard) so deleting the application will not remove the pdf form the SDCard. Use a File Manager app (pn Android) to delete the file

Remember to make sure you have a PDF viewer installed on your Android device or emulator

function doClick(e) {
//alert($.label.text);
openPDF();
}
function viewPDF(appfilepath) {
if(OS_ANDROID) {
try{
Ti.Android.currentActivity.startActivity(Ti.Android.createIntent({
action: Ti.Android.ACTION_VIEW,
type: 'application/pdf',
data: appfilepath
}));
} catch(e) {
Ti.API.info('error trying to launch activity, e = '+e);
alert('No PDF apps installed!');
}
} else {
docViewer = Ti.UI.iOS.createDocumentViewer({url:appfilepath});
docViewer.show();
}
}
function openPDF() {
var appFile;
if(OS_ANDROID) {
appFile = Ti.Filesystem.getFile(Ti.Filesystem.externalStorageDirectory, 'map.pdf');
} else {
appFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, 'map.pdf');
}
Ti.API.info('appFile = '+appFile);
var appfilepath = appFile.nativePath;
Ti.API.info('appFile.nativePath = '+appFile.nativePath);
if(appFile.exists()===false) {
Ti.API.info('file is empty');
var xhr = Ti.Network.createHTTPClient();
xhr.onload = function() {
Ti.API.info('xhr onload event');
appFile.write(this.responseData);
viewPDF(appfilepath);
};
xhr.onerror = function() {
Ti.API.info('xhr error event');
};
xhr.timeout = 10000;
xhr.open("GET", "https://www.mbta.com/uploadedfiles/Documents/Schedules_and_Maps/Rapid%20Transit%20w%20Key%20Bus.pdf");
xhr.send();
} else {
Ti.API.info('file exists');
viewPDF(appfilepath);
}
}
$.index.open();
".container": {
backgroundColor:"white"
}
"Label": {
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
color: "#000"
}
"#label": {
font: {
fontSize: 12
}
}
<Alloy>
<Window class="container">
<Label id="label" onClick="doClick">Open PDF</Label>
</Window>
</Alloy>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment