How to print only part of HTML? [duplicate]

2

To print a page I know I should use

<button onclick="window.print()">

What I need to know is how to start a DIV?

Ex:

<div id="divtoprint">
   //some code
</div>
    
asked by anonymous 25.11.2017 / 02:41

3 answers

2

There are several ways to do this, some with JavaScript, some with CSS only. A good way is to start with the simplest, just like this CSS-only solution, posted by Bennett McElwee on the English OS : / p>

@media print {
  body * {
    visibility: hidden;
  }
  #section-to-print, #section-to-print * {
    visibility: visible;
  }
  #section-to-print {
    position: absolute;
    left: 0;
    top: 0;
  }
}
    
25.11.2017 / 03:01
1

The function below will open a popup with only the contents of the% specified% to print, and will also apply the external CSS if there is:

Button to print with div of id :

<button onclick="printDIV('divtoprint')">Imprimir</button>

JavaScript:

function printDIV(i){
   var cssEstilos = '';
   var imp = window.open('', 'div', 'width='+window.innerWidth+',height='+window.innerWidth);

   var cSs = document.querySelectorAll("link[rel='stylesheet']");
   for(x=0;x<cSs.length;x++){
      cssEstilos += '<link rel="stylesheet" href="'+cSs[x].href+'">';
   }

   imp.document.write('<html><head><title>' + document.title  + '</title>');
   imp.document.write(cssEstilos+'</head><body>');
   imp.document.write(document.getElementById(i).innerHTML);
   imp.document.write('</body></html>');

   setTimeout(function(){
      imp.print();
      imp.close();
   },500);
}

Note: The div tag to load your external CSS must have the <link> attribute. Ex.:

<link rel="stylesheet" href="estilo.css">
    
25.11.2017 / 03:52
0

There are several ways to do this, since you want JavaScript, here is a simple example.

<body>
<div id="sua_div">Essa é a DIV</div>
<button id="btn">Clique para imprimir</button>

<script>
document.getElementById('btn').onclick = function() {
   var conteudo = document.getElementById('sua_div').innerHTML,
   tela_impressao = window.open('about:blank');

   tela_impressao.document.write(conteudo);
   tela_impressao.window.print();
   tela_impressao.window.close();
};
</script>
</body>

I hope I have helped. Here is just one base, but it can be improved.

    
25.11.2017 / 03:07