c# 网页打印全流程

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

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

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

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

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DocumentPrint.aspx.cs" Inherits="Abroad_DocumentPrint" EnableViewState="false" %>
 2 
 3 <html xmlns="http://www.w3.org/1999/xhtml" >
 4 <head runat="server">
 5 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
 6 
 7    <title>打印</title>
 8    <link href="../css/print.css" rel="stylesheet" type="text/css" />
 9 </head>
10 <body onload="PageSetup_Null()">
11     <form id="form1" runat="server">
12     <object  id="WebBrowser"  width=0  height=0  classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2">
13 </object>    
14     <div class="printbar">
15     <div style="float:right">
16         <a href="javascript:void(0)" onclick="print()"><img src="../images/printbutton.gif" border=0 / alt="打印"></a>
17         <a href="javascript:void(0)" onclick="printtrainmember()" runat="server" id="btprinttmember"><img src="../images/printbutton.gif" border=0 / alt="打印培训人员" ></a>
18         &nbsp;&nbsp;<a href="javascript:void(0)" onclick="printPreview()" ><img src="../images/printpreviewbutton.gif" border=0 / alt="打印预览"></a>
19         &nbsp;&nbsp;<a href="javascript:void(0)" onclick="window.close()"><img src="../images/closebutton.gif" border=0 / alt="打印"></a>
20         </div>
21     </div>
22     <div id="pPrintContent" runat="server">
23     错误,没有内容!请检查调用参数是否正确.
24     </div>
25     </form>
26 </body>
27 <script src="../js/print.js" type="text/javascript"></script>
28  <script type="text/javascript">
29 var HKEY_Root,HKEY_Path,HKEY_Key;
30 HKEY_Root="HKEY_CURRENT_USER";
31 HKEY_Path="\\Software\\Microsoft\\Internet Explorer\\PageSetup\\";
32 //设置网页打印的页眉页脚为空
33 function PageSetup_Null()
34 {
35      try
36      {
37           var Wsh=new ActiveXObject("WScript.Shell");
38           
39           HKEY_Key="header";
40           Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,"");
41           HKEY_Key="footer";
42           Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,"");
43           
44           HKEY_Key="margin_left"     
45           Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,0);
46               
47           HKEY_Key="margin_top"     
48           Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,0); 
49            
50           HKEY_Key="margin_right"     
51           Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,0);   
52            
53           HKEY_Key="margin_bottom"     
54           Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,0);
55           
56           HKEY_Key="orientation"     
57           Wsh.RegWrite(HKEY_Root+HKEY_Path+HKEY_Key,2);         
58           
59      } 
60     catch(e)
61     {}
62 }
63 </script>
64 </html>
View Code

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()中的代码:

1 protected void Page_Load(object sender, EventArgs e)
2     {
3         btprinttmember.Visible = false;
4         IPrintable print = new DocumentPrint(GetDocument());
5         pPrintContent.InnerHtml = print.Print();
6 
7     }
View Code

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 - 1; i >= 0; 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 - 1; i >= 0; 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;
    }
View Code

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

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

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();
        }
View Code

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

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

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

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

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

posted @ 2017-06-14 17:26  爱生活,爱代码  阅读(3506)  评论(1编辑  收藏  举报