今天公司让做一个打印功能,就是把gridview中的内容打印出来,再网上查了好多方法,最后决定把gridview包含到一个div中,然后将div的html提交到另一个页面,最终打印这个页面.
打印指定内容:
<html>
<head>
<script type="text/javascript" language="javascript">
function printPage() {
var newWin = window.open('printer','','');
var titleHTML = document.getElementById("printdiv").innerHTML;
newWin.document.write(titleHTML);
newWin.document.location.reload();
newWin.print();
newWin.close();
}
</script>
</head>
<body>
<div id="printdiv">
<table class="sontable" cellspacing="0" cellpadding="0" style="width: 13%">
<tr>
<td style="width: 700px; height: 161px">
<asp:GridView ID="GridData" runat="server" CellPadding="3" CellSpacing="0" BorderWidth="1px" BackColor="LightSteelBlue" BorderColor="White" BorderStyle="None" Font-Size="12px" Width="543px" Height="20px" OnRowDataBound="GridData_RowDataBound">
<RowStyle BackColor="GhostWhite" BorderColor="#006699" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" Wrap="True" />
<HeaderStyle Height="25px" BackColor="#006699" Font-Bold="True" ForeColor="White" HorizontalAlign="Center" CssClass="Freezing"/>
</asp:GridView>
</td>
</tr>
</table>
</div>
<a href="javascript:;" οnclick="printPage()">打印</a>
</body>
</html>
代码就是这样的.
第二种方法是,先将页面上的除了你要打印的标签外隐藏,接着执行打印,在打印后将页面上的标签全部显示
代码如下:
function printer()
{
beforeprint();
window.focus();
window.print()
afterprint();
}
方法二
页局部打印GridView 收藏
----------------------------------------
<script language="javascript">
<!--
function PrintNote()
{
var PrintWin=window.open('about:blank','Print');
PrintWin.document.write('<object id="WebBrowser" width=0 height=0 classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>' + document.all("PrintContent").innerHTML);
PrintWin.document.all.WebBrowser.ExecWB(7,1);
PrintWin.close();
}
-->
</script>
--------------------------------------------
内容用<div>装起来,并把DIV设置ID
<div id="PrintContent" align="center">
your GridView
</div>
------------------------------------
<input οnclick="javascript:PrintNote();" type="button" value="打印" id="Button2" onserverclick="Button2_ServerClick" runat="server"/>
把gridvie控件放入DIV里就可以实现打印了。