Skip to content

Instantly share code, notes, and snippets.

@estevanio
Last active June 14, 2016 22:44
Show Gist options
  • Save estevanio/d19dee5b88053a2627d215e175cf073f to your computer and use it in GitHub Desktop.
Save estevanio/d19dee5b88053a2627d215e175cf073f to your computer and use it in GitHub Desktop.
var app=angular.module('app', []);
app.factory('PrintSvc', ['$rootScope', '$compile', '$document', '$http', '$timeout', '$q', function($rootScope, $compile, $document, $http, $timeout, $q) {
var printHtml = function(html) {
var deferred = $q.defer();
var iframe = document.createElement('iframe');
iframe.setAttribute("style", "display: none;");
$document.find('body').eq(0).append(iframe);
var hiddenframe = $document.find('iframe')[0];
hiddenframe.contentWindow.printAndRemove = function() {
hiddenframe.contentWindow.print();
hiddenframe.remove();
};
var htmlContent = "<!doctype html>" +
"<html>" +
'<body onload="printAndRemove();">' +
html +
'</body>' +
"</html>";
var doc = hiddenframe.contentWindow.document.open("text/html", "replace");
doc.write(htmlContent);
deferred.resolve();
doc.close();
return deferred.promise;
};
var printUrl = function(templateUrl, data) {
$http.get(templateUrl).success(function(template) {
var printScope = $rootScope.$new();
angular.extend(printScope, data);
var element = $compile(angular.element('<div>' + template + '</div>'))(printScope);
var waitForRenderAndPrint = function() {
if (printScope.$$phase || $http.pendingRequests.length) {
$timeout(waitForRenderAndPrint);
} else {
printHtml(element.html());
printScope.$destroy();
}
};
waitForRenderAndPrint();
});
};
var printTmpl = function(template, data) {
var printScope = $rootScope.$new();
angular.extend(printScope, data);
var element = $compile(angular.element('<div>' + template + '</div>'))(printScope);
var waitForRenderAndPrint = function() {
if (printScope.$$phase) {
$timeout(waitForRenderAndPrint);
} else {
printHtml(element.html());
printScope.$destroy();
}
};
waitForRenderAndPrint();
};
return {
printUrl: printUrl,
printTmpl: printTmpl
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment