如何打印具有原始样式的HTML元素?

时间:2019-09-06 16:26:32

标签: javascript jquery html css angular

我正在尝试使用window.print();打印HTML元素 但在查看html时没有原始样式。我该如何解决?

printInvoice() {
    var mywindow = window.open("", "PRINT");

    mywindow.document.write("<html>");
    mywindow.document.write("<body>");
    mywindow.document.write($("#html2pdf")[0].outerHTML);
    mywindow.document.write("</body></html>");

    mywindow.document.close();
    mywindow.focus();

    mywindow.print();
    mywindow.close();

    return true;
  }

css:

@media print {
  #invoice {
    padding: 30px;
  }

  .invoice {
    position: relative;
    background-color: #fff;
    min-height: 680px;
    padding: 15px;
  }

  .invoice header {
    padding: 10px 0;
    margin-bottom: 20px;
    border-bottom: 1px solid #3989c6;
  }
}

2 个答案:

答案 0 :(得分:1)

渲染基于html,css和js进行。这就是为什么在新页面中需要全部这三个原因。

假设您的css和js只在头部,您可以执行以下操作

printInvoice() {
    var mywindow = window.open("", "PRINT");

    mywindow.document.head.append(document.head)
    mywindow.document.body.innerHTML = $("#html2pdf")[0].outerHTML;
    mywindow.focus();
    mywindow.print();
    mywindow.close();

    return true;
  }

答案 1 :(得分:0)

谢谢你们的帮助,以下是对我有用的东西:

 printInvoice() {
    var mywindow = window.open("", "PRINT");

    mywindow.document.write("<html>");

    mywindow.document.write(document.head.outerHTML);
    mywindow.document.write("<body>");
    mywindow.document.write(document.getElementById("html2pdf").outerHTML);
    mywindow.document.write("</body></html>");

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
  }

在CSS文件中,使用

设置打印页面的样式
@media print {...}