i have a div
function imprSelec(historial){
var ficha=document.getElementById(historial);
var ventimp=window.open(' ','popimpr');
ventimp.document.write(ficha.innerHTML);
ventimp.document.close();
ventimp.print();
ventimp.close();
}
<div id="historial">
<h3><center>Mi contenido</center></h3>
...
</div>
<a href="javascript:imprSelec('historial')">Imprimir</a>
And I want to print it, I've tried like this but it doesn't work for me, in fact it doesn't do anything. But I want only the content of the div to be printed, historial
preserving the styles of the div.
I add images:
This is how it looks on the web
And this is how it looks, it's more or less fine since I've put the styles directly in the attribute, although the background colors don't work well for me.
Try this function:
And calling it as follows:
Personally, I'm still looking for a cross browser solution to this problem. By default, styles are not considered when printing in most browsers. In the case of Chrome, I haven't even
media="all"
been able to get the styles to be preserved.I guess at some point this will be standardized, allowing printing with full CSS support. Meanwhile, we must find ways to emulate this task.
One way to achieve this is to convert the document to canvas and then to an image (by default PNG) via
HTMLCanvasElement#toDataURL
. Once this is done, all you have to do is add the image to a tag<img>
and print the document.The main problem is that there is no way to prevent the user from printing in the conventional way through the browser menu, so you must make sure to give a visible option at all times to print the content.
I give you an example using the html2canvas library and the event
keydown
to intercept the combinationCtrl + p
that is a quick access to the browser's print option, so that we can prevent the default print and instead, let's do ours. Bootstrap is also used to see the quality of the rendering.The only thing you would have to do is make sure you have permissions for popups. This can be avoided by doing it in the same document, before calling
window#print
the screenshot is put and the parent node is deleted, and after calling it, the node is put again. It may have some limitations if you are using reactive frameworks like React or Vue.Note : Apparently StackOverflow blocks popups in your editor. I have made a Pen so you can see it in operation.
Support
All browsers that implement Canvas :
It's not perfect, but it's a lot better than the default print.