asp.net中打印指定控件内容

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);
}
}
}

 

asp.net中打印指定控件内容,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。