是否有一种从HTML页面打印div的Angular方法?

时间:2013-10-28 14:23:40

标签: javascript jquery html css angularjs

我有一个使用AngularJS的html页面,我想从中打印一个div。有角度的方式吗? ..或者它只是下面的经典JavaScript方式:

    <script language="javascript" type="text/javascript">
    function printDiv(divID) {
        //Get the HTML of div
        var divElements = document.getElementById(divID).innerHTML;
        //Get the HTML of whole page
        var oldPage = document.body.innerHTML;

        //Reset the page's HTML with div's HTML only
        document.body.innerHTML =
        "<html><head><title></title></head><body>" +
        divElements + "</body>";

        //Print Page
        window.print();

        //Restore orignal HTML
        document.body.innerHTML = oldPage;
        }
    </script> 

如果AngularJS没有任何相关内容,你可以建议吗?不使用JavaScript函数(例如:doc.getElementById())..一种接近AngularJS方法的方法吗?

THX,

3 个答案:

答案 0 :(得分:16)

我创建了一个使用iframe技术打印div内容的简单指令。它有点hackish,但效果很好。在我看来,没有比这更好的方法了。指令脚本是:

'use strict';

angular.module('yourAppNameHere').directive('printDiv', function () {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      element.bind('click', function(evt){    
        evt.preventDefault();    
        PrintElem(attrs.printDiv);
      });

      function PrintElem(elem)
      {
        PrintWithIframe($(elem).html());
      }

      function PrintWithIframe(data) 
      {
        if ($('iframe#printf').size() == 0) {
          $('html').append('<iframe id="printf" name="printf"></iframe>');  // an iFrame is added to the html content, then your div's contents are added to it and the iFrame's content is printed

          var mywindow = window.frames["printf"];
          mywindow.document.write('<html><head><title></title><style>@page {margin: 25mm 0mm 25mm 5mm}</style>'  // Your styles here, I needed the margins set up like this
                          + '</head><body><div>'
                          + data
                          + '</div></body></html>');

          $(mywindow.document).ready(function(){
            mywindow.print();
            setTimeout(function(){
              $('iframe#printf').remove();
            },
            2000);  // The iFrame is removed 2 seconds after print() is executed, which is enough for me, but you can play around with the value
          });
        }

        return true;
      }
    }
  };
});

在模板中,您可以像这样标记打印按钮:

<a href="#" print-div=".css-selector-of-the-div-you-want-to-print">Print!</a>

就是这样,它应该有效。 最糟糕的部分是iFrame在一定的毫秒之后被移除,因为没有跨浏览器方式来检测打印执行的结束,因此您需要猜测它需要多长时间才能运行。

你可能需要包含jQuery才能工作,我不确定,因为没有它我几乎不会工作。我添加了一些内联注释以使事情更清晰。我使用了this answer中的一些代码,它使用弹出窗口来打印div内容(但在Angular.js之外)。也许你会更喜欢这种方法。

答案 1 :(得分:5)

我需要这个在IE8 +

中工作
'use strict';

angular
.module('print-div', [])
.directive('printDiv', function () {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            var iframe;
            var elementToPrint = document.querySelector(attrs.printDiv);

            if (!window.frames["print-frame"]) {
                var elm = document.createElement('iframe');
                elm.setAttribute('id', 'print-frame');
                elm.setAttribute('name', 'print-frame');
                elm.setAttribute('style', 'display: none;');
                document.body.appendChild(elm);
            }

            function write(value) {
                var doc;
                if (iframe.contentDocument) { // DOM
                    doc = iframe.contentDocument;
                } else if (iframe.contentWindow) { // IE win
                    doc = iframe.contentWindow.document;
                } else {
                    alert('Wonder what browser this is... ' + navigator.userAgent);
                }
                doc.write(value);
                doc.close();
            }

            element.bind('click', function(event) {
                iframe = document.getElementById('print-frame');
                write(elementToPrint.innerHTML);

                if (window.navigator.userAgent.indexOf ("MSIE") > 0) {
                    iframe.contentWindow.document.execCommand('print', false, null);
                } else {
                    iframe.contentWindow.focus();
                    iframe.contentWindow.print();
                }
            });
        }
    };
});

答案 2 :(得分:-1)

angularPrint是一个角度指令,它非常易于使用。 https://github.com/samwiseduzer/angularPrint

您只需使用自定义属性修饰html:

<div>
  <div print-section>
    I'll print
    <p>Me, too!</p>
  </div>
  <div>I won't</div>
</div>