Hello everyone, Today's I am going to share an interesting article somebody asked to me in my forum, Is there an Angular way of printing a div section from a HTML page?
I was say to him yes but I don't want how, now I study about it and going to share the detail about the PRINT to inner html templates using Angular.
//This is print method $scope.printTo = function (printSectionId) { var innerContents = document.getElementById(printSectionId).innerHTML; var popupWinindow = window.open('', '_blank','width=600,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no'); popupWinindow.document.open(); popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + innerContents + '</html>'); popupWinindow.document.close(); }
HTML code:
<button ng-click="printTo('printSectionId')" class="button">Print</button>
The Full Live (HTML + AngularJs) code sample as given below
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>AngularJS Print Directive of html templates </title> <link rel="stylesheet" href="style.css" /> <script src="https://code.angularjs.org/1.4.1/angular.js"></script> <script> var app = angular.module('myApp', []); app.controller('myCtrl', function ($scope) { //This is print method $scope.printTo = function (printSectionId) { var innerContents = document.getElementById(printSectionId).innerHTML; var popupWinindow = window.open('', '_blank','width=600,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no'); popupWinindow.document.open(); popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + innerContents + '</html>'); popupWinindow.document.close(); } }); </script> </head> <body id="printSectionId" ng-app="myApp"> <div ng-controller="myCtrl"> <h1>AngularJS Print html templates</h1> <form novalidate> First Name:<input type="text" ng-model="firstName" class="tb8"> Last Name:<input type="text" ng-model="lastName" class="tb8"> <button ng-click="Submit()" class="button">Submit</button> <button ng-click="printTo('printSectionId')" class="button">Print</button> </form> </div> </body> </html>
The output: