首页 > Web开发 > 详细

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

时间:2014-04-04 11:02:56      阅读:613      评论:0      收藏:0      [点我收藏+]

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中打印指定控件内容,布布扣,bubuko.com

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

原文:http://www.cnblogs.com/zhangs1986/p/3644018.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!