我有一个使用angularJS的单页Web应用程序。我需要打印某个页面的div。我尝试了以下方法:
该页面包含少量div(print.html)
<div> <div> Do not print </div> <div id="printable"> Print this div </div> <button ng-click="printDiv('printableArea');">Print Div</button> </div>
控制器具有以下脚本:
$scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; }
此代码可打印所需的div,但存在问题。该语句document.body.innerHTML = originalContents;代替了整个应用程序的主体,因为它是SPA。因此,当我刷新页面或再次单击“打印”按钮时,页面的全部内容将被删除。
document.body.innerHTML = originalContents;
$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(); }