简体   繁体   中英

Print the contents of a div - with stylesheet

I want to generate printing innerHTML elements of a div by javascript, so I wrote some code based on these answers . But I want to add another function: I want the printed elements to include not only the innerHTML of the div but its css from <stylesheet> as well. So I modified the code as below, but it doesn't seem to be working well.

<style>
#divID {
    some css...
}
<style>

function printdiv() {
    var headstr = "<html><head><title>file_name</title></head><body>";
    var footstr = "</body></html>";
    var newstrstyle = document.getElementsByTagName("style")[0].innerHTML; // is this right?
    var newstr = document.getElementById('divID').innerHTML;
    var oldstr = document.body.innerHTML;
    document.body.innerHTML = headstr + '<style>' + newstrstyle + '</style>' + newstr + footstr;
    window.print();
    document.body.innerHTML = oldstr;
    return false;
}

I want to bring the CSS from stylesheet instead of adding style values into the string, because what I'm working on has editable css. How should I improve the code?

The problem is that newstr contains the content of the div , but the div with the id "divID" itself not. It follows that the #divID css selector won't match to any div -s, so the styles will not be applied.

To fix this the "<div id='divID'>" itself needs to be added, so the fixed function looks following:

function printdiv() {
  var headstr = "<html><head><title>file_name</title></head><body>";
  var footstr = "</body></html>";
  var newstrstyle = document.getElementsByTagName("style")[0].innerHTML; // is this right? -> yes it is
  var newstr = document.getElementById("divID").innerHTML;
  var oldstr = document.body.innerHTML;
  document.body.innerHTML =
    headstr +
    "<style>" +
    newstrstyle +
    "</style>" +
    "<div id='divID'>" + // this div was missing
    newstr +
    "</div>" + // closing the added div
    footstr;
  window.print();
  document.body.innerHTML = oldstr;
  return false;
}

If you want to check a live example, here is the stackblitz code where I figured it out: https://stackblitz.com/edit/js-madufb?file=index.js

  1. there is no need to create a new window,you just need to hide other elements when print,add this:
    <style media="print">
        body>*:not(.mydiv){
            display: none;
        }
        .mydiv{display: block;}
    </style>

or this in ref css file if link to outer css

@media print{
body>*:not(.none){
    display: none;
}
.none{display: block;}

}

  1. then change the function to this:
    function printDiv{window.print()}
  1. if you dont want to show div in html which you want to print,you can add style to hide it:
    <style>.mydiv{display: none;}</style>

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