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);
}
}
}
公众号【一个码农的日常】 技术群:319931204 1号群: 437802986 2号群: 340250479
出处:http://zhangs1986.cnblogs.com/
码云:https://gitee.com/huanzui
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。