<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>
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);
}
<script id="print-header" type="text/x-jquery-tmpl">
<html>
<header>
<title>Printing Para {num}</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style>
body {
max-width: 300px;
}
</style>
</header>
<body onload="window.print()">
<h2>Printing Para {num} </h2>
<h4>https://math.tools</h4>
</script>
<script id="print-footer" type="text/x-jquery-tmpl">
</body>
</html>
</script>
<script>
$('.printthis').click(function() {
num = $(this).attr("data-id");
w = window.open();
w.document.write(
$("#print-header").html().replace("{num}",num) +
$("#para-" + num).html() +
$("#print-footer").html()
);
w.document.close();
w.focus();
//w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window.
///w.close(); Don't do this otherwise chrome won't work
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a>
<a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a>
<p class="para" id="para-1">
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>
<p class="para" id="para-2">
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>
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
+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')
function printDiv(divID) {
//Get the HTML of div
var divElements = document.getElementById(divID).innerHTML;
//Get the HTML of whole page
var oldPage = document.body.innerHTML;
//Reset the page's HTML with div's HTML only
document.body.innerHTML =
"<html><head><title></title></head><body>" +
divElements + "</body>";
//Print Page
window.print();
//Restore orignal HTML
document.body.innerHTML = oldPage;
}
<script type="text/javascript">
function printDiv() {
var divToPrint = document.getElementById('printArea');
//Firefox was just opening a new window with same content as opener and not performing the printing dialog, so needed to make it open a new instance of the window opener
newWin= window.open(self.location.href);
//We want to format the document appropriately
newWin.document.write("\<!DOCTYPE html\>\<html lang='es'\>\<head\>\<meta charset='utf-8'\/\>\<meta name='viewport' content='width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no'><meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'\>\<meta name='HandheldFriendly' content='true'\/\>");
//HTML ELEMENTS THAT WE WANT TO HIDE FROM THE PRINTING AREA
newWin.document.write("<style type='text/css'>@media print{.dataTables_info,.dataTables_filter{height:0!important;width:0!important;margin:0!important;padding:0!important;min-height:0!important;line-height:0!important;overflow:visible!important;visibility:hidden}");
//General Styling for Printing
newWin.document.write("body {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:0;top:0!important;left:0!important;margin:0!important;orphans:0!important;widows:0!important;overflow:visible!important;page-break-after:always}");
//Some forced styling in css rules includying page break for a div
newWin.document.write("body h1{font-size:1em; font-family:Verdana;} a.marked{color:black; text-decoration:none} .pagebreak { page-break-before: always; } ");
newWin.document.write("@page{size:A4; margin:2em; orphans:0!important;widows:0!important}}</style>\<\/head>\<body>");
newWin.document.write(divToPrint.innerHTML);
newWin.document.write("</body></html>");
newWin.focus();
newWin.print();
}
</script>
HTML比;身体
<div id="printArea">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
<!-- Page break -->
<div class="pagebreak"> </div>
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</div>