由于项目需要,要作打印,而且并不是网页上的现实内容都要打印出来,只打印部分内容。
下面贴出实现代码供大家分享。本事例只打印<!--startprint-->被打印 <!--endprint-->中的内容。
页面代码:Print.aspx
<!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>IE直接打印</title>
<script type="text/javascript" language="javascript">
function preview()
{
bdhtml=window.document.body.innerHTML;
sprnstr="<!--startprint-->";
eprnstr="<!--endprint-->";
prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
window.document.body.innerHTML=prnhtml;
window.print();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
本部分以上不被打印
<!--startprint-->
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
<!--endprint-->
本部分以下不被打印
<div>
<input type="button" name="print" value="预览并打印" οnclick="preview()" />
</div>
</center>
</div>
</form>
</body>
</html>
.cs页面代码:
protected void Page_Load(object sender, EventArgs e)
{
this.GridView1.DataSource = CreateTable();
this.GridView1.DataBind();
}
/// <summary>
/// 创建DataTable
/// </summary>
/// <returns></returns>
private DataTable CreateTable()
{
//定义表
DataTable tb = new DataTable("newTB");
DataColumn column;
DataRow row;
//创建id列
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
//将id列添加到表
tb.Columns.Add(column);
//创建ParentItem列
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ParentItem";
column.AutoIncrement = false;
column.Caption = "ParentItem";
column.ReadOnly = false;
column.Unique = false;
//将ParentItem列添加到表
tb.Columns.Add(column);
//填充数据
for (int i = 0; i <= 2; i++)
{
row = tb.NewRow();
row["id"] = i;
row["ParentItem"] = "ParentItem " + i;
tb.Rows.Add(row);
}
//返回Table
return tb;
}