1.写一个PrintHelper类
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Web.SessionState;
namespace PrintPage
{
public class PrintHelper
{
public PrintHelper()
{ }
public static void PrintWebControl(Control control)
{
PrintWebControl(control, string.Empty);
}
public static void PrintWebControl(Control control, string Script)
{
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWrite);
if (control is WebControl)
{
Unit w = new Unit(100, UnitType.Percentage);
((WebControl)control).Width = w;
}
Page pg = new Page();
pg.EnableEventValidation = false;
if (Script != string.Empty)
{
pg.ClientScript.RegisterStartupScript(pg.GetType(), "PrintJavaScipt", Script);
}
HtmlForm frm = new HtmlForm();
pg.Controls.Add(frm);
frm.Attributes.Add("runat", "server");
frm.Controls.Add(control);
pg.RenderControl(htmlWriter);
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();
}
}
}
2.创建Default页:
放置一个按钮btnPrint与一个Panel,Panel中是要打印的内容
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace PrintPage
{
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["control"] = Panel1;
ClientScript.RegisterStartupScript(this.GetType(), "onclick", "<script language=javascript>window.open('Print.aspx','PrintMe','height=300px,width=300px,scrollbars=1');</script>");
}
}
}
创建Print页面:
在form_load事件中调用打印事件:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace PrintPage
{
public partial class Print : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Control control = (Control)Session["control"];
PrintHelper.PrintWebControl(control);
}
}
}
本文转自欢醉博客园博客,原文链接http://www.cnblogs.com/zhangs1986/p/3644018.html如需转载请自行联系原作者
欢醉