6

I want to print a content of a html div and currently i am using this code.

<div id="content">
</div>

var printContents = document.getElementById("content").innerHTML;
var originalContents = document.body.innerHTML;

document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;

printing is working correctly. But after that my other functions are stop responding. I'm using angular.js.

any idea?

denny
  • 197
  • 1
  • 1
  • 11
  • I don't think so. The user marked it as the solution, which might mean some other users might not find the answer using the same keywords. – Hanlet Escaño Aug 02 '16 at 05:22

2 Answers2

4

Here is the answer I found

HTML and JS CODE

 <div id="printable">
    Print this div
  </div>
  <button ng-click="printDiv('printableArea');">Print Div</button>


$scope.printDiv = function(divName) {
  var printContents = document.getElementById(divName).innerHTML;
  var popupWin = window.open('', '_blank', 'width=300,height=300');
  popupWin.document.open();
  popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
  popupWin.document.close();
} 

I found it from here

Community
  • 1
  • 1
The Mechanic
  • 2,301
  • 1
  • 26
  • 37
0

if you are using angularjs use

<div ng-bind-html="content |trustAs">
</div>

in your controller

$scope.content='<div> Your html</div>';  

app.filter('trustAs', ['$sce', 
        function($sce) {
            return function (input, type) {
                if (typeof input === "string") {
                    return $sce.trustAs(type || 'html', input);
                }
                console.log("trustAs filter. Error. input isn't a string");
                return "";
            };
        }
    ]);

Working fiddle

You can also use ng-sanitize to get the same result https://stackoverflow.com/a/25679834/3769965

Ebin Manuval
  • 1,235
  • 14
  • 33