简体   繁体   English

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

[英]how can I print HTML element with it's original style?

I am trying to print HTML element using window.print(); 我正在尝试使用window.print();打印HTML元素window.print(); but the html is viewed without the original style. 但在查看html时没有原始样式。 how can I fix it? 我该如何解决?

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: 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;
  }
}

Rendering happens based on html, css, and js. 渲染基于html,css和js进行。 This is why you need all these three in your new page. 这就是为什么在新页面中需要全部这三个原因的原因。

Assuming that Your css and js is only in the head, you can do the following 假设您的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;
  }

Thank you guys for helping, following is what worked for me: 谢谢大家的帮助,以下是对我有用的方法:

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

in your css file, style you print page using 在css文件中,使用以下样式设置打印页面的样式

@media print {...} 

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

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