I have a page and in it the content I want to print.
I created a command in JavaScript, but this command makes the whole page print.
Is there any way to print only the contents of a div
?
I have a page and in it the content I want to print.
I created a command in JavaScript, but this command makes the whole page print.
Is there any way to print only the contents of a div
?
It is not possible to select a div
for printing with JavaScript, because this is not a function of it. There is a solution that uses only CSS:
@media print {
body * {
visibility: hidden;
}
#printable, #printable * {
visibility: visible;
}
#printable {
position: fixed;
left: 0;
top: 0;
}
}
In this way, only what is inside this printable
element in HTML will be displayed.
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();
This code should only be executed when triggering some mouse event, otherwise the popup blocker will block the action.
It works very well. Test!
Fiddle: link
In short:
<script>
function cont(){
var conteudo = document.getElementById('print').innerHTML;
tela_impressao = window.open('about:blank');
tela_impressao.document.write(conteudo);
tela_impressao.window.print();
tela_impressao.window.close();
}
</script>
<div id="print" class="conteudo">
// conteúdo a ser impresso pode ser um form ou um table.
</div>
<input type="button" onclick="cont();" value="Imprimir Div separadamente">
function printDiv(divID) {
//pega o Html da DIV
var divElements = document.getElementById(divID).innerHTML;
//pega o HTML de toda tag Body
var oldPage = document.body.innerHTML;
//Alterna o body
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Imprime o body atual
window.print();
//Retorna o conteudo original da página.
document.body.innerHTML = oldPage;
}
And you can also use a popup.
function printDiv(divID)
{
var conteudo = document.getElementById(divID).innerHTML;
var win = window.open();
win.document.write(conteudo);
win.print();
win.close();//Fecha após a impressão.
}
The solutions presented above are not as flexible. They have at least one of the listed problems:
Here is my solution using jQuery:
JS Code:
function printBy(selector){
var $print = $(selector)
.clone()
.addClass('print')
.prependTo('body');
// Stop JS execution
window.print();
// Remove div once printed
$print.remove();
}
CSS style:
@media print {
html, body {
margin: 0;
padding: 0;
border: 0;
}
#printable {
margin: 0;
padding: 0;
border: 0;
font-size: 14px;
}
#printable ~ * {
display: none;
}
}