简体   繁体   English

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

[英]Is there an Angular way of printing a div from a HTML page?

I have an html page using AngularJS, and I want to print a div from it. 我有一个使用AngularJS的html页面,我想从中打印一个div。 Is there an Angular way of doing it? 有角度的方式吗? .. or it`s just the classic javascript way below: ..或者它只是下面的经典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> 

If AngularJS doesn't have anything around this, can you suggest o way of doing it, without using JavaScript functions (ex: doc.getElementById() ).. an approach close to the AngularJS way ? 如果AngularJS没有任何相关内容,你能不提出使用JavaScript函数的建议吗(例如:doc.getElementById())..一种接近AngularJS方法的方法吗?

Thx, 谢谢,

I have created a simple directive for printing div contents using the iframe technique. 我已经创建了一个使用iframe技术打印div内容的简单指令。 It's a bit hackish, but works very well. 它有点hackish,但效果很好。 there is no better way to do it in my opinion. 在我看来,没有比这更好的方法了。 The directive script is: 指令脚本是:

'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;
      }
    }
  };
});

In your template you mark the print button like this: 在模板中,您可以将打印按钮标记为:

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

And that's it, it should work. 就是这样,它应该工作。 The hackish part is that the iFrame is removed after a certain number of miliseconds as there is no cross-browser way to detect the end of the print execution, so you guestimate how much time would be needed for it to run. hackish部分是在一定数量的毫秒后删除iFrame,因为没有跨浏览器方式来检测打印执行的结束,因此您需要猜测它需要多长时间才能运行。

You may need to include jQuery for it to work, I'm not sure as I almost never work without it. 您可能需要包含jQuery才能工作,我不确定,因为没有它我几乎不会工作。 I added some inline comments to make things clearer. 我添加了一些内联注释以使事情更清晰。 I used some code from this answer that uses a popup to print div content (but outside of Angular.js). 我使用了这个答案中的一些代码,它使用弹出窗口来打印div内容(但在Angular.js之外)。 Maybe you'll like that approach more. 也许你会更喜欢这种方法。

I needed this to work in IE8+ 我需要这个在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();
                }
            });
        }
    };
});

angularPrint is an angular directive that's super easy to use. angularPrint是一个超级易用的角度指令。 https://github.com/samwiseduzer/angularPrint https://github.com/samwiseduzer/angularPrint

you simply decorate your html with its custom attributes: 你只需用自定义属性装饰你的html:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM