c# 网页打印全流程

时间:2023-03-09 22:30:11
c# 网页打印全流程

说明:我要实现的就是将数据库中Group表的数据查找出来,替换打印模版中的内容,再将模版文件打印出来

1、准备好要打印的模版group_O_train.html

 <div  class="pagetitle title">出国(境)培训人员汇总表</div>
<div>项目编号:{项目编号}</div>
<table class="pagedtable" style="width:25cm;font-size:9pt;border-collapse:collapse;" cellspacing= cellpadding=3px border= bordercolor=black>
<thead style="text-align:center">
<tr>
<td style="width:0.6cm">序号</td>
<td style="width:1.5cm">姓 名</td>
<td style="width:0.8cm">性别</td>
<td style="width:2.0cm">出 生<br />年月日</td>
<td style="width:1.5cm">出生地</td>
<td style="width:1.0cm">政治面貌</td>
<td style="width:4.5cm">工作单位</td>
<td style="width:2.7cm">职务或<br />职 称</td>
<td style="width:4cm">何年毕业于<br />何校、何专业</td>
<td style="width:2cm">目前从事的<br />实际工作</td>
<td style="width:1.0cm">备注</td>
</tr>
</thead>
<tbody>
{人员名单}
</tbody>
</table>
<p class="alignright" style="width:25cm">出国(境)归口管理部门公章</p>

2、打印通用页面,其中<div id="pPrintContent" runat="server">是模版要替换的内容

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DocumentPrint.aspx.cs" Inherits="Abroad_DocumentPrint" EnableViewState="false" %>

 <html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title>打印</title>
<link href="../css/print.css" rel="stylesheet" type="text/css" />
</head>
<body onload="PageSetup_Null()">
<form id="form1" runat="server">
<object id="WebBrowser" width= height= classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2">
</object>
<div class="printbar">
<div style="float:right">
<a href="javascript:void(0)" onclick="print()"><img src="../images/printbutton.gif" border= / alt="打印"></a>
<a href="javascript:void(0)" onclick="printtrainmember()" runat="server" id="btprinttmember"><img src="../images/printbutton.gif" border= / alt="打印培训人员" ></a>
&nbsp;&nbsp;<a href="javascript:void(0)" onclick="printPreview()" ><img src="../images/printpreviewbutton.gif" border= / alt="打印预览"></a>
&nbsp;&nbsp;<a href="javascript:void(0)" onclick="window.close()"><img src="../images/closebutton.gif" border= / alt="打印"></a>
</div>
</div>
<div id="pPrintContent" runat="server">
错误,没有内容!请检查调用参数是否正确.
</div>
</form>
</body>
<script src="../js/print.js" type="text/javascript"></script>
<script type="text/javascript">
var HKEY_Root,HKEY_Path,HKEY_Key;
HKEY_Root="HKEY_CURRENT_USER";
HKEY_Path="\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
//设置网页打印的页眉页脚为空
function PageSetup_Null()
{
try
{
var Wsh=new ActiveXObject("WScript.Shell"); HKEY_Key="header";
Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,"");
HKEY_Key="footer";
Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,""); HKEY_Key="margin_left"
Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,); HKEY_Key="margin_top"
Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,); HKEY_Key="margin_right"
Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,); HKEY_Key="margin_bottom"
Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,); HKEY_Key="orientation"
Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,); }
catch(e)
{}
}
</script>
</html>

3、在你所要打印的页面加上打印的按钮,

<a id="btPrint" href="javascript:void(0)" title="打印报批件" onclick="printGroup();" class="linkbutton">【打 印】</a>

4、点击打印后会调用printGroup()方法,该方法写在同一文档的JS中

   function printGroup()
{
openPrintDocument(groupId,"group");
}
function openPrintDocument(activityId,type)
{
window.open("../ForeignActivity/documentprint.aspx?a="+Math.random()+"&id="+activityId+"&type="+type,"",'width=820,height=750,left=50,top=50,menubar=yes,scrollbars=yes,resizable=yes,help=no,status=no;',true);
}

5、这里所打开的documentprint.aspx文件也就是我们之前准备好的通用模版文件,在显示这个文件之前我们必须要获取另一个我们准备好的模版文件group_O_train.html,将这个文件追加到<div id="pPrintContent" runat="server">标签中

1)documentprint.aspx.cs 中 page_Load()中的代码:

 protected void Page_Load(object sender, EventArgs e)
{
btprinttmember.Visible = false;
IPrintable print = new DocumentPrint(GetDocument());
pPrintContent.InnerHtml = print.Print(); }

2)在1)调用的GetDocument()方法获取文档

private IOutPutWithTemplate GetDocument()
{
IOutPutWithTemplate one=null;
string type = GetDocumentTypeName();
type = type.ToLower();
switch (type)
{
case "rwpj":
RWPJService service = new RWPJService();
one = service.GetByGroupId(Id);
break;
case "gfh":
GFHService gfhService = new GFHService();
one = gfhService.GetByGroupId(Id);
break;
case "rwqrj":
RWQRJService service2 = new RWQRJService();
one = service2.GetByGroupId(Id);
break;
case "zqyjfh":
ZQYJFHService service3 = new ZQYJFHService();
one = service3.GetByGroupId(Id);
break;
case "groupwithsolution": //带审批意见的打印
GroupService gservice = new GroupService();
GZWGroupInfo group = (GZWGroupInfo)gservice.GetDetailGroupInfoById(Id);
if (group.IsTrain) btprinttmember.Visible = true;
one = new PrintApprovalSolutionDecorator(group);
break;
case "group":
GroupService gservice2 = new GroupService();
GZWGroupInfo group2 = (GZWGroupInfo)gservice2.GetDetailGroupInfoById(Id);
one = new PrintApprovalSolutionDecorator(group2);
break;
case "rwtzs":
RWTZSService tzsService = new RWTZSService();
one = tzsService.GetById(Id);
break;
case "zqyjh":
ZQYJHService yjhService = new ZQYJHService();
one = yjhService.GetById(Id);
break;
case "wth":
WTHService wthService = new WTHService();
one = wthService.GetById(Id);
break;
case "hzk":
HZKService hzkService = new HZKService();
one = hzkService.GetById(Id);
break;
case "cjzm":
CJZMService cjzmService = new CJZMService();
one = cjzmService.GetOneById(Id);
break;
case "qzh":
QZHService qzhService = new QZHService();
one = qzhService.GetById(Id);
qzhService.FillChildren((QZH)one);
break;
case "ywzh":
YWZHService ywzhService = new YWZHService();
one = ywzhService.GetById(Id);
ywzhService.FillChildren((YWZH)one);
break;
case "pqh":
PQHService pqhService = new PQHService();
one = pqhService.GetById(Id);
pqhService.FillChildren((PQH)one);
break;
case "checkdrawbill":
TicketReservation ticketReservation = new TicketReservationService().GetOneById(Id);
one = new CheckDrawBillPrint(ticketReservation, "CheckDrawBill");
break;
case "ticketpassportinfo":
TicketReservation ticketReservation2 = new TicketReservationService().GetOneById(Id);
one = new TicketPassportInfoPrint(ticketReservation2, "TicketPassportInfo");
break;
case "ticketreservationprint":
TicketReservation ticketReservation3 = new TicketReservationService().GetOneById(Id);
one = new TicketReservationPrint(ticketReservation3, "TicketReservationPrint");
break;
case "zsbackup":
ZSInfo zsInfo = ZSService.GetById(Id);
one = new ZSInfoPrint(zsInfo, "zsbackup");
break;
//case "zsgroups":
// GroupService SimpleGroupService = new GroupService();
// one = new ZSInfoGroupPrint((GZWGroupInfo)SimpleGroupService.GetSimpleGroupInfoById(Id));
// break;
case "zspj":
ZSPJ zspj = ZSPJService.GetByGroupId(Id);
one = new ZSPJPrint(zspj, "zspj");
break;
case "groupforapplypassport": //打印护照申办用的团组表
one = GroupPrint.CreateFromGroup(Id);
break;
case "unuploadplan":
List<PlanBase> templists = new List<PlanBase>();
UnitInfo unitInfo = UnitService.GetUnitByCode(Profile.UnitCode);
string plantype = Request.QueryString["planType"];
if (string.IsNullOrEmpty(plantype))
break; if (plantype.ToLower() == "general")//不含培训(包含汇总表打印和考察表打印)
{
List<PlanBase> hzlists = new List<PlanBase>();
PlanProcess process = new GeneralPlanProcess();
hzlists.AddRange(process.GetPlansByYear(unitInfo, Id, PlanType.ForUpload, PlanStatus.NotUploaded));
hzlists.AddRange(process.GetPlansByYear(unitInfo, Id, PlanType.ForUpload, PlanStatus.Retrial));
List<PlanBase> kclists = new List<PlanBase>();
kclists.AddRange(process.GetPlansByYearAndPurpose(unitInfo, Id, PlanType.ForUpload, PlanStatus.NotUploaded, "考察"));
kclists.AddRange(process.GetPlansByYearAndPurpose(unitInfo, Id, PlanType.ForUpload, PlanStatus.Retrial, "考察"));
GeneralPlanProcess gprocess = new GeneralPlanProcess();
for (int i = hzlists.Count - ; i >= ; i--)
{
GeneralPlan gp = hzlists[i] as GeneralPlan;
//保存打印时间
gp.HzPrintTime = DateTime.Now;
gprocess.SavePlan(gp);
}
foreach (PlanBase p in kclists)
{
GeneralPlan gp = (GeneralPlan)p;
gp.KcPrintTime = DateTime.Now;
gprocess.SavePlan(gp);
}
one = new PrintGeneralPlan(hzlists, kclists, Id, Profile.Name, Profile.Phone, "PrintGeneralPlan"); }
else if (plantype.ToLower() == "sp")//审批
{
PlanProcess processBySp = new SPPlanProcess();
templists.AddRange(processBySp.GetPlansByYear(unitInfo, Id, PlanType.ForUpload, PlanStatus.NotUploaded));
templists.AddRange(processBySp.GetPlansByYear(unitInfo, Id, PlanType.ForUpload, PlanStatus.Retrial)); //保存打印时间
foreach (PlanBase p in templists)
{
SPPlan sp = (SPPlan)p;
sp.PrintTime = DateTime.Now;
new SPPlanProcess().SavePlan(sp);
}
one = new PrintSPPlan(templists, Id, Profile.Name, Profile.Phone, "PrintSPPlan");
}
else//审核
{
PlanProcess processBySh = new SHPlanProcess();
templists.AddRange(processBySh.GetPlansByYear(unitInfo, Id, PlanType.ForUpload, PlanStatus.NotUploaded));
templists.AddRange(processBySh.GetPlansByYear(unitInfo, Id, PlanType.ForUpload, PlanStatus.Retrial));
//保存打印时间
foreach (PlanBase p in templists)
{
SHPlan sp = (SHPlan)p;
sp.PrintTime = DateTime.Now;
new SHPlanProcess().SavePlan(sp);
}
one = new PrintSHPlan(templists, Id, Profile.Name, Profile.Phone, "PrintSHPlan");
} break;
case "plan":
List<PlanBase> templist = new List<PlanBase>();
UnitInfo unit = UnitService.GetUnitByCode(Profile.UnitCode);
string ptype = Request.QueryString["planType"];
if (string.IsNullOrEmpty(ptype))
break; if (ptype.ToLower() == "general")//不含培训(包含汇总表打印和考察表打印)
{
List<PlanBase> hzlists = new List<PlanBase>();
PlanProcess process = new GeneralPlanProcess();
hzlists.AddRange(process.GetPlansByYear(unit, Id, PlanType.ForUpload, PlanStatus.Uploaded));
hzlists.AddRange(process.GetPlansByYear(unit, Id, PlanType.ForUpload, PlanStatus.ReUploaded));
List<PlanBase> kclists = new List<PlanBase>();
kclists.AddRange(process.GetPlansByYearAndPurpose(unit, Id, PlanType.ForUpload, PlanStatus.Uploaded, "考察"));
kclists.AddRange(process.GetPlansByYearAndPurpose(unit, Id, PlanType.ForUpload, PlanStatus.ReUploaded, "考察"));
GeneralPlanProcess gprocess = new GeneralPlanProcess();
if (!Rules.CanManagerPlan())
{
for (int i = hzlists.Count - ; i >= ; i--)
{
GeneralPlan gp = hzlists[i] as GeneralPlan;
//保存打印时间
gp.HzPrintTime = DateTime.Now;
gprocess.SavePlan(gp);
}
foreach (PlanBase p in kclists)
{
GeneralPlan gp = (GeneralPlan)p;
gp.KcPrintTime = DateTime.Now;
gprocess.SavePlan(gp);
}
}
one = new PrintGeneralPlan(hzlists, kclists, Id, Profile.Name, Profile.Phone, "PrintGeneralPlan");
}
else if (ptype.ToLower() == "sp")//审批
{
PlanProcess processBySp = new SPPlanProcess();
templist.AddRange(processBySp.GetPlansByYear(unit, Id, PlanType.ForUpload, PlanStatus.Uploaded));
templist.AddRange(processBySp.GetPlansByYear(unit, Id, PlanType.ForUpload, PlanStatus.ReUploaded));
if (!Rules.CanManagerPlan())
{
//保存打印时间
foreach (PlanBase p in templist)
{
SPPlan sp = (SPPlan)p;
sp.PrintTime = DateTime.Now;
new SPPlanProcess().SavePlan(sp);
}
}
one = new PrintSPPlan(templist, Id, Profile.Name, Profile.Phone, "PrintSPPlan");
}
else//审核
{
PlanProcess processBySh = new SHPlanProcess();
templist.AddRange(processBySh.GetPlansByYear(unit, Id, PlanType.ForUpload, PlanStatus.Uploaded));
templist.AddRange(processBySh.GetPlansByYear(unit, Id, PlanType.ForUpload, PlanStatus.ReUploaded));
if (!Rules.CanManagerPlan())
{
//保存打印时间
foreach (PlanBase p in templist)
{
SHPlan sp = (SHPlan)p;
sp.PrintTime = DateTime.Now;
new SHPlanProcess().SavePlan(sp);
}
}
one = new PrintSHPlan(templist, Id, Profile.Name, Profile.Phone, "PrintSHPlan");
} break;
case "qzxxb":
QZSXB qzsxb = QZSXBService.GetQZSXBById(Id);
//one = QZSXBService.Print(docID);
one = new QZXXBPrint(qzsxb);
break;
case "qzxxbmember":
QZSXBMember qzsxbMember = QZSXBService.GetMemberById(Id);
one = new QZXXBMemberPrint(qzsxbMember);
break;
case "qzxxbcountry":
QZSXBCountry qzsxbCountry = QZSXBService.GetCountryById(Id);
one = new QZXXBCountryPrint(qzsxbCountry);
break;
case "chinesenote":
one = new ChineseNoteService().GetById(Id);
break;
}
return one;
}

3) 在2)中调用GetDocumentTypeName()方法获取文档类型,类弄为“group”

private string GetDocumentTypeName()
{
return Request.Params["type"];
}

4) 在2)中调用GetDetailGroupInfoById(Id)方法,根据ID号获取到Group表的数据

5) 在2)中调用PrintApprovalSolutionDecorator(group2)方法是对这些数据进行处理,也就是去填充模版

在这个类中首先要确定这个模版文件的名称,这里确定的是group_O_train.html文件

6)读文件

/// <summary>
/// 按照对象的类型名称来获取模版,规则是打开 对象类型名称.html文件,读取其中的内容
/// </summary>
/// <param name="type">类型名称(字符串,比如:group,budget)</param>
/// <returns></returns>
static public string GetTemplateFromFile(string type)
{
string fileName = HttpContext.Current.Server.MapPath("../Template/" +type+ ".html");
return ReadTemplateFromFile(fileName);
} /// <summary>
/// 读取文件
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
static private string ReadTemplateFromFile(string fileName)
{
if (!File.Exists(fileName))
{
throw new ApplicationException(fileName + "不存在");
}
System.Text.StringBuilder rtn = new System.Text.StringBuilder();
using (StreamReader sr = File.OpenText(fileName))
{
String input;
while ((input = sr.ReadLine()) != null)
{
rtn.Append(input);
}
sr.Close();
}
return rtn.ToString();
}

7)在1)中调用Print()方法是它会去调OutPut(string template)方法

string IPrintable.Print()
{
return document.OutPut(this.Template);
}

OutPut(string template)方法是IOutPutWithTemplate的一个接口

8)在类PrintApprovalSolutionDecorator中实现了OutPut(string template)方法,在这个方法中对模版文件中的占位符进行了替换

9)在1)中pPrintContent.InnerHtml = print.Print();就是将group_O_train.html追加到DocumentPrint.aspx中,最后将DocumentPrint.aspx页面展示出来,也就是我们要打印的页面。