【问题标题】:Angular 2 printing a componentAngular 2打印组件
【发布时间】:2017-06-18 11:45:47
【问题描述】:

在纯 JavaScript 中,您可以通过获取元素 ID、将其放入新窗口并使用 window.print() 来打印元素。

做这种事情的“Angular 2”方法是什么?我已经获得了我希望打印的组件的 ViewChild,但我不确定如何访问它的 html 并随后打印它,或者这是否是我应该做的。

【问题讨论】:

  • 我发现最好的方法是创建你的打印组件,在你的路由中给它一个最高层次的路由。使用 window.open(url) 打开路由。并在该组件 afterviewinit 调用 window.print() 。在视图创建打印后,您可以将任何组件包含到打印组件中。不要忘记在打印组件上添加 css @media print{}。

标签: angular


【解决方案1】:

如果你需要打印一些自定义的 HTML,这个方法不需要新窗口。

ts:

    let control_Print;

    control_Print = document.getElementById('__printingFrame');

    let doc = control_Print.contentWindow.document;
    doc.open();
    doc.write("<div style='color:red;'>I WANT TO PRINT THIS, NOT THE CURRENT HTML</div>");
    doc.close();

    control_Print = control_Print.contentWindow;
    control_Print.focus();
    control_Print.print();

html:

<iframe title="Lets print" id="__printingFrame" style="width: 0; height: 0; border: 0"></iframe>

【讨论】:

    【解决方案2】:

    HTML

        <div id="printSection"></div>
        <button (click)="print()">PRINT</button>
    

    TS

        print(): void {
           let printContents, popupWin;
           printContents = document.getElementById('printSection').innerHTML;
           popupWin = window.open('', '_blank', 'top=0,left=0,height=100%,width=auto');
           popupWin.document.open();
           popupWin.document.write(`
              <html>
                  <head>
                      <title>Print tab</title>
                      <style>
                          //........Customized style.......
                      </style>
                  </head>
                  <body onload="window.print();window.close()">${printContents}
                  </body>
              </html>`
           );
           popupWin.document.close();
        }
    

    【讨论】:

    • 好的。我可以理解为什么有人会否决这个答案(出于多种原因)但是..这是现在完美的锤子!
    • 这只是从类似问题stackoverflow.com/questions/41379274/…接受的答案的复制粘贴
    猜你喜欢
    • 2017-10-29
    • 1970-01-01
    • 2017-05-13
    • 2019-03-04
    • 1970-01-01
    • 2017-05-23
    • 2016-04-14
    • 1970-01-01
    • 2016-11-08
    相关资源
    最近更新 更多