JavaScript实现的一段打印页面的通用JS代码.具体原理就是将当前页面的innerHTML内容导入到通用打印页面中,然后调用前台ActiveX对象实现页面内容的打印.假设通用打印页面为网站根目录下的CommonPage/Print.aspx,JS代码如下:
var win=null,arr=null;
function PrintPage(url, arrPara)
{
win = window.open(document.location.pathname.substr(0,document.location.pathname.substr(1).indexOf('/')+1) + "/CommonPage/Print.aspx", "打印", "top=0,left=0,width=1024,height=800,toolbar=no, menubar=no, scrollbars=yes, resizable=yes,location=no, status=no");
arr = arrPara;
window.setTimeout("CheckPrintData()",50);
return win;
}
function CheckPrintData()
{
if(win.document.getElementById("Div_Data") == null)
{
window.setTimeout("CheckPrintData()",50);
return;
}
if(document.all.form1 == null)
{
alert("页面没有名称为'form1'的Form元素,打印失败!");
return;
}
win.document.getElementById("Div_Data").innerHTML=document.all.form1.innerHTML;
for(var i=0; i<arr.length; i++)
{
if(win.document.getElementById(arr) != null)
{
win.document.getElementById(arr).style.display = "none";
}
}
if((win.document.location.href.toUpperCase().indexOf("JS_MANAGE")!=-1 ||
win.document.location.href.toUpperCase().indexOf("HS_MANAGE")!=-1 ||
win.document.location.href.toUpperCase().indexOf("ZL_MANAGE")!=-1) &&
win.document.all.xls!=null)
{
for(var i=0;i<document.all.xls.rows.length;i++)
{
win.document.all.xls.rows(i).deleteCell(0);
}
}
win.document.all.MyWebBrowser.ExecWB(7,1);
win.window.close();
}
通用打印页面(Print.aspx)的代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Print.aspx.cs" Inherits="Print" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>通用打印页面</title>
<script type="text/javascript" language="javascript">
var showNum = 0;
function Check()
{
if(showNum++ > 0)
{
close();
}
}
</script>
</head>
<body onfocus="Check();">
<form id="form1" runat="server">
<object id="MyWebBrowser" classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2" height="0"
width="0">
</object>
<div id="Div_Data">
<br />
<br />
<br />
页面加载中,请稍候...<br />
</div>
</form>
</body>
</html>