<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
var hkey_root, hkey_path, hkey_key;
hkey_root = "HKEY_CURRENT_USER";
hkey_path = "\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
function setup_null() {
try {
var RegWsh = new ActiveXObject("WScript.Shell")
hkey_key = "header"
RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "")
hkey_key = "footer"
RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "")
} catch (e) {}
}
function setup_default() {
try {
var RegWsh = new ActiveXObject("WScript.Shell")
hkey_key = "header"
RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "&w&b页码,&p/&P")
hkey_key = "footer"
RegWsh.RegWrite(hkey_root + hkey_path + hkey_key, "&u&b&d")
} catch (e) {}
}
function doPrint(printDiv) {
try {
setup_null();
newwin = window.open("", "newwin", "height=" + window.screen.height + ",width=" + window.screen.width +
",toolbar=no,scrollbars=auto,menubar=no");
newwin.document.body.innerHTML = document.getElementById(printDiv).innerHTML;
newwin.window.print();
newwin.window.close();
setup_default();
} catch (e) {}
}
function printPage() {
setup_null();
bdhtml = window.document.body.innerHTML;
sprnstr = "<!--start-->";
eprnstr = "<!--end-->";
printhtml = bdhtml.substr(bdhtml.indexOf(sprnstr) + 17);
printhtml = printhtml.substring(0, printhtml.indexOf(eprnstr));
f = document.getElementById('printf');
f.contentDocument.write(printhtml);
f.contentDocument.close();
f.contentWindow.print();
}
</script>
</head>
<body>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<h3>xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</h3>
<input type="button" value="打印" onClick="printPage()" />
<iframe id="printf" src="" width="0" height="0" frameborder="0"></iframe>
</div>
</body>
</html>
- 由于window.print();在调用打印机的时候会修改页面的dom,导致内容改变,为了让用户在进行预览打印的同时不修改dom内容,最好的解决办法就是用iframe新建一个窗口,将要打印的内容写入到iframe中(f.contentDocument.write(printhtml))在新打开的iframe中调用浏览器的打印机就解决了此问题(f.contentWindow.print());
- 多数打印都是表格,默认情况下单元格之间会存在着间距,需要加上
border-collapse: collapse
属性 - 对于打印样式的设置,推荐直接写到标签上,对于其他博客上的加入
media="print"
引入css,我没有尝试成功,直接写到标签上。