





















客户端打印页面内容的2种方法,
方法一:用js 来实现
代码
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title>无标题页</title>
<script type="text/javascript" language="javascript">
function printSpecial()
{
var html = '<HTML>\n<HEAD>\n';if (document.getElementsByTagName != null)
{
var headTags = document.getElementsByTagName("head");
if (headTags.length > 0)
html += headTags[0].innerHTML;
}
html
+= '\n</HEAD>\n<BODY>\n<div style="height:150px;"></div>';var printReadyElem = document.getElementById("printPart");if (printReadyElem != null)方法2:通过后台代码实现(使用MSChart, updatePanel 会有问题), 这种方法其实和方法一一样。
主页面前台代码
代码
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClick="btnPrint_Click" />
<asp:Panel ID="Panel1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Test Print"></asp:Label>
</asp:Panel>
主页面后台代码
代码
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnPrint_Click(object sender, EventArgs e)
{
Session["ctrl"] = this.Panel1;
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=600px,width=800px,scrollbars=1');</script>");
}
}
打印页面后台代码:
代码
protected void Page_Load(object sender, EventArgs e)
{
PrintHelper.PrintWebControl((Control)Session["ctrl"]);
}
打印方法:
代码
using System.Web.UI.DataVisualization.Charting;
/// <summary>
///PrintHelper 的摘要说明
/// </summary>
public class PrintHelper
{
public PrintHelper()
{
}
public static void PrintWebControl(Control ctrl)
{
PrintWebControl(ctrl, string.Empty);
}public static void PrintWebControl(Control ctrl, string Script)
{
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
if (ctrl is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage); ((WebControl)ctrl).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;
if (Script != string.Empty)
{
pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScript", Script);
}
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(ctrl);
pg.DesignerInitialize();
pg.RenderControl(htmlWrite);
string strHTML = stringWrite.ToString();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write(strHTML);
HttpContext.Current.Response.Write("<script>window.print();</script>");
HttpContext.Current.Response.End();
}
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。