Whats the best way to print the contents of a DIV?
This question is related to
javascript
jquery
html
printing
I modified @BillPaetski answer to use querySelector, add optional CSS, remove the forced H1 tag and make title optionally specified or pulled from window. It also doesn't auto-print any more and exposes internals so they can be switched out in wrapper function or as you like.
The only two private vars are tmpWindow and tmpDoc although I believe title, css and elem access may vary it should be assumed all function arguments are private.
Code:function PrintElem(elem, title, css) {
var tmpWindow = window.open('', 'PRINT', 'height=400,width=600');
var tmpDoc = tmpWindow.document;
title = title || document.title;
css = css || "";
this.setTitle = function(newTitle) {
title = newTitle || document.title;
};
this.setCSS = function(newCSS) {
css = newCSS || "";
};
this.basicHtml5 = function(innerHTML) {
return '<!doctype html><html>'+(innerHTML || "")+'</html>';
};
this.htmlHead = function(innerHTML) {
return '<head>'+(innerHTML || "")+'</head>';
};
this.htmlTitle = function(title) {
return '<title>'+(title || "")+'</title>';
};
this.styleTag = function(innerHTML) {
return '<style>'+(innerHTML || "")+'</style>';
};
this.htmlBody = function(innerHTML) {
return '<body>'+(innerHTML || "")+'</body>';
};
this.build = function() {
tmpDoc.write(
this.basicHtml5(
this.htmlHead(
this.htmlTitle(title) + this.styleTag(css)
) + this.htmlBody(
document.querySelector(elem).innerHTML
)
)
);
tmpDoc.close(); // necessary for IE >= 10
};
this.print = function() {
tmpWindow.focus(); // necessary for IE >= 10*/
tmpWindow.print();
tmpWindow.close();
};
this.build();
return this;
}
Usage:
DOMPrinter = PrintElem('#app-container');
DOMPrinter.print();
Created something generic to use on any HTML element
HTMLElement.prototype.printMe = printMe;
function printMe(query){
var myframe = document.createElement('IFRAME');
myframe.domain = document.domain;
myframe.style.position = "absolute";
myframe.style.top = "-10000px";
document.body.appendChild(myframe);
myframe.contentDocument.write(this.innerHTML) ;
setTimeout(function(){
myframe.focus();
myframe.contentWindow.print();
myframe.parentNode.removeChild(myframe) ;// remove frame
},3000); // wait for images to load inside iframe
window.focus();
}
//usage
document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();
Hope this helps.
function printdiv(printdivname) {
var headstr = "<html><head><title>Booking Details</title></head><body>";
var footstr = "</body>";
var newstr = document.getElementById(printdivname).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
This will print the div
area you want and set the content back to as it was. printdivname
is the div
to be printed.
If you want to have all the styles from the original document (including inline styles) you can use this approach.
Implementation:
class PrintUtil {
static printDiv(elementId) {
let printElement = document.getElementById(elementId);
var printWindow = window.open('', 'PRINT');
printWindow.document.write(document.documentElement.innerHTML);
setTimeout(() => { // Needed for large documents
printWindow.document.body.style.margin = '0 0';
printWindow.document.body.innerHTML = printElement.outerHTML;
printWindow.document.close(); // necessary for IE >= 10
printWindow.focus(); // necessary for IE >= 10*/
printWindow.print();
printWindow.close();
}, 1000)
}
}
The best way to do it would be to submit the contents of the div to the server and open a new window where the server could put those contents into the new window.
If that's not an option you can try to use a client-side language like javascript to hide everything on the page except that div and then print the page...
i used Bill Paetzke
answer to print a div contain images but it didn't work with google chrome
i just needed to add this line myWindow.onload=function(){
to make it work and here is the full code
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js"> </script>
<script type="text/javascript">
function PrintElem(elem) {
Popup($(elem).html());
}
function Popup(data) {
var myWindow = window.open('', 'my div', 'height=400,width=600');
myWindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
myWindow.document.write('</head><body >');
myWindow.document.write(data);
myWindow.document.write('</body></html>');
myWindow.document.close(); // necessary for IE >= 10
myWindow.onload=function(){ // necessary if the div contain images
myWindow.focus(); // necessary for IE >= 10
myWindow.print();
myWindow.close();
};
}
</script>
</head>
<body>
<div id="myDiv">
This will be printed.
<img src="image.jpg"/>
</div>
<div>
This will not be printed.
</div>
<div id="anotherDiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintElem('#myDiv')" />
</body>
</html>
also if someone just need to print a div with id he doesn't need to load jquery
here is pure javascript code to do this
<html>
<head>
<script type="text/javascript">
function PrintDiv(id) {
var data=document.getElementById(id).innerHTML;
var myWindow = window.open('', 'my div', 'height=400,width=600');
myWindow.document.write('<html><head><title>my div</title>');
/*optional stylesheet*/ //myWindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
myWindow.document.write('</head><body >');
myWindow.document.write(data);
myWindow.document.write('</body></html>');
myWindow.document.close(); // necessary for IE >= 10
myWindow.onload=function(){ // necessary if the div contain images
myWindow.focus(); // necessary for IE >= 10
myWindow.print();
myWindow.close();
};
}
</script>
</head>
<body>
<div id="myDiv">
This will be printed.
<img src="image.jpg"/>
</div>
<div>
This will not be printed.
</div>
<div id="anotherDiv">
Nor will this.
</div>
<input type="button" value="Print Div" onclick="PrintDiv('myDiv')" />
</body>
</html>
i hope this can help someone
I authored a plugin to address this scenario. I was unhappy with the plugins out there, and set out to make something more extensive/configurable.
Here is an IFrame solution that works for IE and Chrome:
function printHTML(htmlString) {
var newIframe = document.createElement('iframe');
newIframe.width = '1px';
newIframe.height = '1px';
newIframe.src = 'about:blank';
// for IE wait for the IFrame to load so we can access contentWindow.document.body
newIframe.onload = function() {
var script_tag = newIframe.contentWindow.document.createElement("script");
script_tag.type = "text/javascript";
var script = newIframe.contentWindow.document.createTextNode('function Print(){ window.focus(); window.print(); }');
script_tag.appendChild(script);
newIframe.contentWindow.document.body.innerHTML = htmlString;
newIframe.contentWindow.document.body.appendChild(script_tag);
// for chrome, a timeout for loading large amounts of content
setTimeout(function() {
newIframe.contentWindow.Print();
newIframe.contentWindow.document.body.removeChild(script_tag);
newIframe.parentElement.removeChild(newIframe);
}, 200);
};
document.body.appendChild(newIframe);
}
Here is my jquery print plugin
(function ($) {
$.fn.printme = function () {
return this.each(function () {
var container = $(this);
var hidden_IFrame = $('<iframe></iframe>').attr({
width: '1px',
height: '1px',
display: 'none'
}).appendTo(container);
var myIframe = hidden_IFrame.get(0);
var script_tag = myIframe.contentWindow.document.createElement("script");
script_tag.type = "text/javascript";
script = myIframe.contentWindow.document.createTextNode('function Print(){ window.print(); }');
script_tag.appendChild(script);
myIframe.contentWindow.document.body.innerHTML = container.html();
myIframe.contentWindow.document.body.appendChild(script_tag);
myIframe.contentWindow.Print();
hidden_IFrame.remove();
});
};
})(jQuery);
I know this is an old question, but I solved this problem w jQuery.
function printContents(id) {
var contents = $("#"+id).html();
if ($("#printDiv").length == 0) {
var printDiv = null;
printDiv = document.createElement('div');
printDiv.setAttribute('id','printDiv');
printDiv.setAttribute('class','printable');
$(printDiv).appendTo('body');
}
$("#printDiv").html(contents);
window.print();
$("#printDiv").remove();
}
CSS
@media print {
.non-printable, .fancybox-outer { display: none; }
.printable, #printDiv {
display: block;
font-size: 26pt;
}
}
Although @BC answer was the best to print a single page.
But To print multiple pages of A4 size at same time with ctrl+P following solution may help.
@media print{
html *{
height:0px!important;
width:0px !important;
margin: 0px !important;
padding: 0px !important;
min-height: 0px !important;
line-height: 0px !important;
overflow: visible !important;
visibility: hidden ;
}
/*assing myPagesClass to every div you want to print on single separate A4 page*/
body .myPagesClass {
z-index: 100 !important;
visibility: visible !important;
position: relative !important;
display: block !important;
background-color: lightgray !important;
height: 297mm !important;
width: 211mm !important;
position: relative !important;
padding: 0px;
top: 0 !important;
left: 0 !important;
margin: 0 !important;
orphans: 0!important;
widows: 0!important;
overflow: visible !important;
page-break-after: always;
}
@page{
size: A4;
margin: 0mm ;
orphans: 0!important;
widows: 0!important;
}}
Note: This works with jQuery enabled sites only
It is very simple with this cool trick. It worked for me in Google Chrome browser. Firefox wont allow you to print to PDF without a plugin.
var jqchild = document.createElement('script');
jqchild.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";
document.getElementsByTagName('body')[0].appendChild(jqchild);
$("#myDivWithStyles").print(); // Replace ID with yours
The logic is simple. We are creating a new script tag and attaching it in front of closing body tag. We injected a jQuery print extension into the HTML. Change myDivWithStyles with your own Div tag ID. Now it takes cares of preparing a printable virtual window.
Try it on any site. Only caveat is sometimes trickily written CSS can cause missing of styles. But we get the content most of times.
I think the solutions proposed so far have the following drawbacks:
I have improved on the solutions above. Here is something that I have tested that works really well with the following benefits.
Key Points to note :
<script id="print-header" type="text/x-jquery-tmpl">_x000D_
<html>_x000D_
<header>_x000D_
<title>Printing Para {num}</title>_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
<style>_x000D_
body {_x000D_
max-width: 300px;_x000D_
}_x000D_
</style>_x000D_
</header>_x000D_
<body onload="window.print()">_x000D_
<h2>Printing Para {num} </h2>_x000D_
<h4>http://math.tools</h4>_x000D_
</script>_x000D_
<script id="print-footer" type="text/x-jquery-tmpl">_x000D_
</body>_x000D_
</html>_x000D_
</script>_x000D_
<script>_x000D_
$('.printthis').click(function() {_x000D_
num = $(this).attr("data-id");_x000D_
w = window.open();_x000D_
w.document.write(_x000D_
$("#print-header").html().replace("{num}",num) +_x000D_
$("#para-" + num).html() +_x000D_
$("#print-footer").html() _x000D_
);_x000D_
w.document.close();_x000D_
w.focus();_x000D_
//w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window._x000D_
///w.close(); Don't do this otherwise chrome won't work_x000D_
});_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a>_x000D_
<a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a>_x000D_
_x000D_
<p class="para" id="para-1">_x000D_
Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
_x000D_
_x000D_
<p class="para" id="para-2">_x000D_
Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
_x000D_
From here http://forums.asp.net/t/1261525.aspx
<html>
<head>
<script language="javascript">
function printdiv(printpage) {
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr + newstr + footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
</script>
<title>div print</title>
</head>
<body>
//HTML Page //Other content you wouldn't like to print
<input name="b_print" type="button" class="ipt" onClick="printdiv('div_print');" value=" Print ">
<div id="div_print">
<h1 style="Color:Red">The Div content which you want to print</h1>
</div>
//Other content you wouldn't like to print //Other content you wouldn't like to print
</body>
</html>
Same as best answer, just in case you need to print image as i did:
In case you want to print image:
function printElem(elem)
{
Popup(jQuery(elem).attr('src'));
}
function Popup(data)
{
var mywindow = window.open('', 'my div', 'height=400,width=600');
mywindow.document.write('<html><head><title>my div</title>');
mywindow.document.write('</head><body >');
mywindow.document.write('<img src="'+data+'" />');
mywindow.document.write('</body></html>');
mywindow.print();
mywindow.close();
return true;
}
The below code copies all relevant nodes that are targeted by the query selector, copies over their styles as seen on screen, since many parent elements used for targeting the css selectors will be missing. This causes a bit of lag if there are a lot of child nodes with a lot of styles.
Ideally you'd have a print style sheet ready, but this is for use cases where there's no print style sheet to be inserted and you wish to print as seen on screen.
If you copy the below items in the browser console on this page it will print all the code snippets on this page.
+function() {
/**
* copied from https://stackoverflow.com/questions/19784064/set-javascript-computed-style-from-one-element-to-another
* @author Adi Darachi https://stackoverflow.com/users/2318881/adi-darachi
*/
var copyComputedStyle = function(from,to){
var computed_style_object = false;
//trying to figure out which style object we need to use depense on the browser support
//so we try until we have one
computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);
//if the browser dose not support both methods we will return null
if(!computed_style_object) return null;
var stylePropertyValid = function(name,value){
//checking that the value is not a undefined
return typeof value !== 'undefined' &&
//checking that the value is not a object
typeof value !== 'object' &&
//checking that the value is not a function
typeof value !== 'function' &&
//checking that we dosent have empty string
value.length > 0 &&
//checking that the property is not int index ( happens on some browser
value != parseInt(value)
};
//we iterating the computed style object and compy the style props and the values
for(property in computed_style_object)
{
//checking if the property and value we get are valid sinse browser have different implementations
if(stylePropertyValid(property,computed_style_object[property]))
{
//applying the style property to the target element
to.style[property] = computed_style_object[property];
}
}
};
// Copy over all relevant styles to preserve styling, work the way down the children tree.
var buildChild = function(masterList, childList) {
for(c=0; c<masterList.length; c++) {
var master = masterList[c];
var child = childList[c];
copyComputedStyle(master, child);
if(master.children && master.children.length > 0) {
buildChild(master.children, child.children);
}
}
}
/** select elements to print with query selector **/
var printSelection = function(querySelector) {
// Create an iframe to make sure everything is clean and ordered.
var iframe = document.createElement('iframe');
// Give it enough dimension so you can visually check when modifying.
iframe.width = document.width;
iframe.height = document.height;
// Add it to the current document to be sure it has the internal objects set up.
document.body.append(iframe);
var nodes = document.querySelectorAll(querySelector);
if(!nodes || nodes.length == 0) {
console.error('Printing Faillure: Nothing to print. Please check your querySelector');
return;
}
for(i=0; i < nodes.length; i++) {
// Get the node you wish to print.
var origNode = nodes[i];
// Clone it and all it's children
var node = origNode.cloneNode(true);
// Copy the base style.
copyComputedStyle(origNode, node);
if(origNode.children && origNode.children.length > 0) {
buildChild(origNode.children, node.children);
}
// Add the styled clone to the iframe. using contentWindow.document since it seems the be the most widely supported version.
iframe.contentWindow.document.body.append(node);
}
// Print the window
iframe.contentWindow.print();
// Give the browser a second to gather the data then remove the iframe.
window.setTimeout(function() {iframe.parentNode.removeChild(iframe)}, 1000);
}
window.printSelection = printSelection;
}();
printSelection('.default.prettyprint.prettyprinted')
In Opera, try:
print_win.document.write('</body></html>');
print_win.document.close(); // This bit is important
print_win.print();
print_win.close();
I think there is a better solution. Make your div to print cover the entire document, but only when it's printed:
@media print {
.myDivToPrint {
background-color: white;
height: 100%;
width: 100%;
position: fixed;
top: 0;
left: 0;
margin: 0;
padding: 15px;
font-size: 14px;
line-height: 18px;
}
}
This is realy old post but here is one my update what I made using correct answer. My solution also use jQuery.
Point of this is to use proper print view, include all stylesheets for the proper formatting and also to be supported in the most browsers.
function PrintElem(elem, title, offset)
{
// Title constructor
title = title || $('title').text();
// Offset for the print
offset = offset || 0;
// Loading start
var dStart = Math.round(new Date().getTime()/1000),
$html = $('html');
i = 0;
// Start building HTML
var HTML = '<html';
if(typeof ($html.attr('lang')) !== 'undefined') {
HTML+=' lang=' + $html.attr('lang');
}
if(typeof ($html.attr('id')) !== 'undefined') {
HTML+=' id=' + $html.attr('id');
}
if(typeof ($html.attr('xmlns')) !== 'undefined') {
HTML+=' xmlns=' + $html.attr('xmlns');
}
// Close HTML and start build HEAD
HTML+='><head>';
// Get all meta tags
$('head > meta').each(function(){
var $this = $(this),
$meta = '<meta';
if(typeof ($this.attr('charset')) !== 'undefined') {
$meta+=' charset=' + $this.attr('charset');
}
if(typeof ($this.attr('name')) !== 'undefined') {
$meta+=' name=' + $this.attr('name');
}
if(typeof ($this.attr('http-equiv')) !== 'undefined') {
$meta+=' http-equiv=' + $this.attr('http-equiv');
}
if(typeof ($this.attr('content')) !== 'undefined') {
$meta+=' content=' + $this.attr('content');
}
$meta+=' />';
HTML+= $meta;
i++;
}).promise().done(function(){
// Insert title
HTML+= '<title>' + title + '</title>';
// Let's pickup all CSS files for the formatting
$('head > link[rel="stylesheet"]').each(function(){
HTML+= '<link rel="stylesheet" href="' + $(this).attr('href') + '" />';
i++;
}).promise().done(function(){
// Print setup
HTML+= '<style>body{display:none;}@media print{body{display:block;}}</style>';
// Finish HTML
HTML+= '</head><body>';
HTML+= '<h1 class="text-center mb-3">' + title + '</h1>';
HTML+= elem.html();
HTML+= '</body></html>';
// Open new window
var printWindow = window.open('', 'PRINT', 'height=' + $(window).height() + ',width=' + $(window).width());
// Append new window HTML
printWindow.document.write(HTML);
printWindow.document.close(); // necessary for IE >= 10
printWindow.focus(); // necessary for IE >= 10*/
console.log(printWindow.document);
/* Make sure that page is loaded correctly */
$(printWindow).on('load', function(){
setTimeout(function(){
// Open print
printWindow.print();
// Close on print
setTimeout(function(){
printWindow.close();
return true;
}, 3);
}, (Math.round(new Date().getTime()/1000) - dStart)+i+offset);
});
});
});
}
Later you simple need something like this:
$(document).on('click', '.some-print', function() {
PrintElem($(this), 'My Print Title');
return false;
});
Try it.
The accepted solution wasn't working. Chrome was printing a blank page because it wasn't loading the image in time. This approach works:
Edit: It appears the accepted solution was modified after my post. Why the downvote? This solution works as well.
function printDiv(divName) {
var printContents = document.getElementById(divName).innerHTML;
w = window.open();
w.document.write(printContents);
w.document.write('<scr' + 'ipt type="text/javascript">' + 'window.onload = function() { window.print(); window.close(); };' + '</sc' + 'ript>');
w.document.close(); // necessary for IE >= 10
w.focus(); // necessary for IE >= 10
return true;
}
Using Jquery, simply use this function:
<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
}
</script>
Your print button will look like this:
<button id="print" onclick="printContent('id name of your div');" >Print</button>
Edit: If you DO have form data that you need to keep, clone won't copy that, so you'll just need to grab all the form data and replace it after restore as so:
<script>
function printContent(el){
var restorepage = $('body').html();
var printcontent = $('#' + el).clone();
var enteredtext = $('#text').val();
$('body').empty().html(printcontent);
window.print();
$('body').html(restorepage);
$('#text').html(enteredtext);
}
</script>
<textarea id="text"></textarea>
Create a separate print stylesheet that hides all other elements except the content you want to print. Flag it using 'media="print"
when you load it:
<link rel="stylesheet" type="text/css" media="print" href="print.css" />
This allows you to have a completely different stylesheet loaded for printouts.
If you want to force the browser's print dialog to appear for the page, you can do it like this on load using JQuery:
$(function() { window.print(); });
or triggered off of any other event you want such as a user clicking a button.
Although this has been said by @gabe,
If you are using jQuery, you can use my printElement
plugin.
There's a sample here, and more information about the plugin here.
The usage is rather straight forward, just grab an element with a jQuery selector and print it:
$("#myDiv").printElement();
I hope it helps!
Just use PrintJS
let printjs = document.createElement("script");
printjs.src = "https://printjs-4de6.kxcdn.com/print.min.js";
document.body.appendChild(printjs);
printjs.onload = function (){
printJS('id_of_div_you_want_to_print', 'html');
}
Source: Stackoverflow.com