0

I have this code. I print the content of a DIV via its ID, but omit an image. I would like your support to know how to make that image be included. (the image is also inside the DIV)

impresion = The DIV to print

function printDiv(impresion) {
     var contenido= document.getElementById(impresion).innerHTML;
     var contenidoOriginal= document.body.innerHTML;


     document.body.innerHTML = contenido;

     window.print();

     document.body.innerHTML = contenidoOriginal;
}

I have tried many things and nothing works

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125

2 Answers2

0

Here is a simple solution using just CSS:

@media print {
  body * {
    visibility: hidden;
  }
  #impresion, #impresion * {
    visibility: visible;
  }
  #impresion {
    position: absolute;
    left: 0;
    top: 0;
  }
}
PataFoos
  • 126
  • 1
  • 6
  • I used it and it partially worked. At the time of printing I get another 2 blank pages. I guess it's because it only "Hide" the body, however it appears blank on other extra sheets. Any other solution? – ArathM15 Nov 15 '22 at 19:15
  • Hmm, then I would test it using display:none and display:block instead of visibility:hidden and visible. (I still don't understand why the image is not being printed in your first example, I've seen other solutions using that approach and they seems to work) – PataFoos Nov 16 '22 at 01:40
  • I tried to use display but now it doesn't show me anything in print view. I used visibility and it worked, but with blank sheets. – ArathM15 Nov 16 '22 at 16:22
0

Try this, using a div with id="impresion":

function Print() {
  let data = document.getElementById("impresion").innerHTML;
  let mywindow = window.open('', 'new div', 'height=400,width=600');
  mywindow.document.write('<html><head><title></title></head><body >');
  mywindow.document.write(data);
  mywindow.document.write('</body></html>');
  setTimeout(function(){mywindow.print()},1000);
  return true;
}
PataFoos
  • 126
  • 1
  • 6
  • It has worked for me! But it has generated me 3 extra pages. I think it's visibility: none that's the problem. Here is my CSS. I would appreciate your support @media print { .container-fluid {width: auto} body * { visibility: hidden; } #imprimir, #imprimir * { visibility: visible; } #imprimir { position: absolute; left: 0; top: 0; } } – ArathM15 Nov 16 '22 at 20:44
  • with this function you don't need that css rules, because in the new generated window there's no elements other than your div content. In case you still need to hide something, you may want to use display: none instead of visibility: hidden – PataFoos Nov 16 '22 at 20:51