简体   繁体   中英

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

I am trying to print HTML element using window.print(); but the html is viewed without the original style. 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:

@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. 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

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

@media print {...} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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