printFrame.js
window.print = printFrame;
function printFrame(frame, onfinish) {
if (!frame) frame = window;
function execOnFinish() {
switch (typeof (onfinish)) {
case "string": execScript(onfinish); break;
case "function": onfinish();
}
if (focused && !focused.disabled) focused.focus();
}
if ((frame.document.readyState !== "complete") && (!frame.document.confirm("The document to print is not downloaded yet! Continue with printing?"))) {
execOnFinish();
return;
}
var eventScope = printGetEventScope(frame);
var focused = document.activeElement;
window.printHelper = function () {
execScript("on error resume next: printWB.ExecWB 6, 1", "VBScript");
printFireEvent(frame, eventScope, "onafterprint");
printWB.outerHTML = "";
execOnFinish();
window.printHelper = null;
}
document.body.insertAdjacentHTML("beforeEnd",
"<object id=\"printWB\" width=0 height=0 \
classid=\"clsid:8856F961-340A-11D0-A96B-00C04FD705A2\">");
printFireEvent(frame, eventScope, "onbeforeprint");
frame.focus();
window.printHelper = printHelper;
setTimeout("window.printHelper()", 0);
}
function printIsNativeSupport() {
var agent = window.navigator.userAgent;
var i = agent.indexOf("MSIE ") + 5;
return parseInt(agent.substr(i)) >= 5 && agent.indexOf("5.0b1") < 0;
}
function printFireEvent(frame, obj, name) {
var handler = obj[name];
switch (typeof (handler)) {
case "string": frame.execScript(handler); break;
case "function": handler();
}
}
function printGetEventScope(frame) {
var frameset = frame.document.all.tags("FRAMESET");
if (frameset.length) return frameset[0];
return frame.document.body;
}
主页面:
<script type="text/javascript" language="javascript" src="../../Scripts/printFrame.js"></script>
<script language="javascript" type="text/javascript">
function printHidden(url) {
document.body.insertAdjacentHTML("beforeEnd", "<iframe name=printHiddenFrame width=0 height=0></iframe>");
var doc = printHiddenFrame.document;
doc.open();
doc.write("<body οnlοad=\"parent.onprintHiddenFrame()\">");
doc.write("<iframe name=printMe width=0 height=0 src=\"" + url + "\"></iframe>");
doc.write("</body>");
doc.close();
}
function onprintHiddenFrame() {
function onfinish() {
printHiddenFrame.outerHTML = "";
if (window.onprintcomplete) window.onprintcomplete();
}
printFrame(printHiddenFrame.printMe, onfinish);
}
</script>
打印按钮事件:指向要打印页的URL
Page.ClientScript.RegisterStartupScript(this.GetType(), "print", "<script>printHidden('PrintPage.aspx')</script>");
打印页面PrintPage:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//绑定页面数据
//打印页面
Page.ClientScript.RegisterStartupScript(this.GetType(), "print", "<script>window.print();</script>");
}
}