Last active
May 9, 2018 21:19
-
-
Save edsonhoraciojunior/ab714a3621aed94936b3392bb9135431 to your computer and use it in GitHub Desktop.
AngularJS - Save remote PDF locally and open it using native PDF Viewer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
'use strict'; | |
angular.module('app.controllers') | |
.controller('PdfDownloadAndViewerCtrl', function( | |
$cordovaFile, | |
$http, | |
$cordovaFileOpener2, | |
$sce | |
){ | |
$scope.view = function(conteudo) { | |
// downloads file | |
var pdfUrl = encodeURI('http://unec.edu.az/application/uploads/2014/12/pdf-sample.pdf'); | |
$http({ | |
url: pdfUrl, | |
method: 'GET', | |
headers: {'Content-Type': 'application/pdf'}, | |
responseType: 'arraybuffer' | |
}).then(function(response) { | |
// create blob | |
try { | |
var blob = new Blob([response.data], {type : "application/pdf"}); | |
} catch(e) { | |
// TypeError old chrome and FF | |
window.BlobBuilder = window.BlobBuilder || | |
window.WebKitBlobBuilder || | |
window.MozBlobBuilder || | |
window.MSBlobBuilder; | |
if (e.name == 'TypeError' && window.BlobBuilder) { | |
var bb = new BlobBuilder(); | |
bb.append(response.data); | |
var blob = bb.getBlob("application/pdf"); | |
} else if (e.name == "InvalidStateError") { | |
// InvalidStateError (tested on FF13 WinXP) | |
var blob = new Blob([response.data], {type : "application/pdf"}); | |
} else { | |
console.log('We\'re screwed, blob constructor unsupported entirely'); | |
return; | |
} | |
} | |
var objectUrl = window.URL || window.webkitURL; | |
var fileURL = objectUrl.createObjectURL(blob); | |
$sce.trustAsResourceUrl(fileURL); | |
var fileName = "test.pdf"; | |
// save file locally | |
$cordovaFile.writeFile(cordova.file.dataDirectory, fileName, blob, true) | |
.then(function (success) { | |
// open pdf with native PDF Viewer | |
var filePath = cordova.file.dataDirectory + fileName; | |
$cordovaFileOpener2.open( | |
filePath, | |
'application/pdf' | |
).then(function() { | |
console.log('file opened successfully'); | |
}, function(err) { | |
console.log('An error occurred. Show a message to the user'); | |
console.log(JSON.stringify(err)); | |
}); | |
}, function (err) { | |
console.log('error saving file'); | |
console.log(JSON.stringify(err)); | |
}); | |
}).catch(function(err) { | |
console.log(JSON.stringify(err)); | |
}); | |
}; | |
}) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment