zoukankan      html  css  js  c++  java
  • B/S C/S 打印

    网络打印概述
    • B/S结构导致了Web应用程序中打印的特殊性。
    • 程序运行在浏览器中,打印机在本地,而文件确可能在服务器上,导致了打印控制
    不是很灵活。
    • 格式如何控制和定制等,是我们开发中可能会面对的问题。

    打印文档的生成
    • 1、客户端脚本方式
    一般情况下,主要使用JS 可以分析源页面的内容,将欲打印的页面元素提取出来,实现打印。通过分析源文档的内容,可以生成打印目标文档。
    优点:客户端独立完成打印目标文档的生成,减轻服务器负荷;
    缺点:源文档的分析操作复杂,并且源文档中的打印内容要有约定。
    • 2、服务器端程序方式
    利用后台代码从数据库中读取打印源,生成打印目标文档。当的页面生成时,还应适当考虑使用CSS 来实现强制分页控制。
    优点:可以生成内容非常丰富的打印目标文档,目标文档的内容的可控性强。由于打印内容是从数据库中获取的,所以生成操作相对简单;
    缺点:服务器端负载比较大;

    页面设置
    • 页面设置主要是指设置打印文档的页边距、页眉、页脚、纸张等内容。页面设置将直接影响到打印文档版面的生成效果,所以它和打印文档的生成有着密切的关系。比如:表格的行数、大小、位置、字体的大小等。
    现有的技术是利用IE6.0 内置的打印模板方式来控制页面设置,其可以对打印目标文档产生非常大的影响。打印模板可以控制页边距、页眉、页脚、奇偶页等内容,并可以将用户的设置取得,还可以将设置发送到服务器端。打印模板技术可以自定预览窗口和打印格式,最大限度地影响目标文档和打印效果。
    IE直接打印
    • 即直接调用window.print或者webrower控件的ExecWB方法来打印。
    • 优点:方便快捷,客户端无需任何设置即可。
    • 缺点:打印控制不是很灵活。如果直接调用

    window.print来打印页面,页面上别的元素也会被打印处理,页头页尾的格式也不好控制。
    • 常用方法:大部分情况会把查询的结果绑定到DataGrid上来,然后打印DataGrid。这种情况的打印一般来说格式比较固定简单,确定后基本不会再作更改。所以可以采用IE直接打印。

    【实例代码】
    注:①这是客户端通过window.print打印指定内容。这里定义sprnstr和eprnstr来指定内容
         执行代码:
        input type="button" name="print" value="预览并打印" onclick="preview()">


         ②如果直接使用window.print将打印页面上的所有内容,但是我们可以使用
    st<<style> @media Print { .Noprn { DISPLAY: none }}
    是用来指定不打印的内容。

    script language="javascript">
    function preview()
    {
        bdhtml=window.document.body.innerHTML;
        sprnstr="<!--startprint-->";
        eprnstr="<!--endprint-->";
        prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
        prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
        window.document.body.innerHTML=prnhtml;
        window.print();
    }
    </script>
    <!--省略部分代码-->
    <form id="WebForm1" method="post" runat="server">
         <center>本部分以上不被打印</center>
         <!--startprint-->
         <div align="center">
             <asp:DataGrid id="dgShow" runat="server">
                  <!--省略部分代码-->
             </asp:DataGrid>
         </div>
         <!--endprint-->
         <center>本部分以下不被打印</center>
         <div align="center">
             <input type="button" name="print" value="预览并打印" onclick="preview()">
         </div>
         <style> @media Print { .Noprn { DISPLAY: none }}
         </style>
         <p class="Noprn">不打印</p>
         <table id="datagrid">
             <tr>
                  <td>打印</td>
             </tr>
         </table>
         <input class="Noprn" type="button" onclick="window.print()" value="print">
    </form>


    WebBrowser 控件技术
    • 打印操作的实现
    此功能的实现主要是利用WebBrowser控件的函数接口来实现打印、打印预览(默认的)、
    页面设置(默认的)。
    <object ID=‘WebBrowser1’ WIDTH=0 HEIGHT=0
    CLASSID=‘CLSID:8856F961-340A-11D0-A96B-00C04FD705A2’>
    //打印
    WebBrowser1.ExecWB(6,1);
    //打印设置
    WebBrowser1.ExecWB(8,1);
    //打印预览
    WebBrowser1.ExecWB(7,1);
    //直接打印
    WebBrowser1.ExecWB(6,6);
    【实例代码】
    //自定义类PrintClass
    public string DGPrint(DataSet ds)
    {
        //DGPrint执行的功能:根据DataTable转换成对应的HTML对应的字符串
         DataTable myDataTable=new DataTable();
         myDataTable=ds.Tables[0];

         int myRow=myDataTable.Rows.Count;
         int myCol=myDataTable.Columns.Count;

         StringBuilder sb=new StringBuilder();

         string colHeaders="<html><body>"+"<object ID='WebBrowser' WIDTH=0 HEIGHT=0 CLASSID='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'VIEWASTEXT></object>" +"<table><tr>";

         for(int i=0;i<myCol;i++)
         {    
             colHeaders +="<td>"+ myDataTable.Columns[i].ColumnName.ToString()+"</td>";
         }
         colHeaders += "</tr>";
         sb.Append(colHeaders);

         for(int i=0;i<myRow;i++)
         {      
             sb.Append("<tr>");
             for(int j=0;j<myCol;j++)
             {
                  sb.Append("<td>");
                  sb.Append(myDataTable.Rows[i][j].ToString().Trim());
                  sb.Append("</td>");
             }
             sb.Append("</tr>");  
         }

         sb.Append("</table></body></html>");
         colHeaders=sb.ToString();              
         colHeaders+="<script languge='javascript'>WebBrowser.ExecWB(6,1); window.opener=null;window.close();</script>";
         return(colHeaders);
    }

    //页面:打印按钮事件
    PrintClass myP = new PrintClass();
    Response.Write(myP.DGPrint(Bind()));

    在把DataGrid转换为对应的HTML代码时,如果存在按钮列就会报错,最好把这一列隐藏,一般只能转换数据列。其次要注意分页问题,一般只能打印当前一页,最好在打印之前除掉分页
    导出到Excel,Word中去打印
    • 可以在服务端或者客户端进行。
    • 优点:使用这种方法,可适应性比较强,控制较好。
    • 缺点:在服务端使用的话,要求服务端要安装Word,Excel,在客户端使用的话,要
    求客户端在IE的安全设置上有一定要求。
    【实例代码】
    protected void btnMIME_Click(object sender, System.EventArgs e)
    {
         BindData();

         Response.ContentType = "application/vnd.ms-excel";
         Response.AddHeader("Content-Disposition", "inline;filename="+HttpUtility.UrlEncode("下载文件.xls",Encoding.UTF8));       

         //如果输出为Word,修改为以下代码
         //Response.ContentType = "application/ms-word"
         //Response.AddHeader("Content-Disposition", "inline;filename=test.doc")
         StringBuilder sb=new StringBuilder();
         System.IO.StringWriter sw = new System.IO.StringWriter(sb);
         System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
         sb.Append("<html><body>");
         dgShow.RenderControl(hw);
         sb.Append("</body></html>");
         Response.Write(sb.ToString());
         Response.End();
    }

    protected void btnCom_Click(object sender, System.EventArgs e)
    {
         ExportToExcel(BindData(),Server.MapPath("ComExcel.xls"));

    }
    //从DataSet到出到Excel
    #region从DataSet到出到Excel
    ///导出指定的Excel文件
    public void ExportToExcel(DataSet ds,string strExcelFileName)
    {
         if (ds.Tables.Count==0 || strExcelFileName=="") return;
         doExport(ds,strExcelFileName);
    }
    ///执行导出
    private void doExport(DataSet ds,string strExcelFileName)
    {
         Excel.Application excel= new Excel.Application();
         int rowIndex=1;
         int colIndex=0;
         excel.Application.Workbooks.Add(true);
         System.Data.DataTable table=ds.Tables[0] ;
         foreach(DataColumn col in table.Columns)
         {
             colIndex++;   
             excel.Cells[1,colIndex]=col.ColumnName;               
         }

         foreach(DataRow row in table.Rows)
         {
             rowIndex++;
             colIndex=0;
             foreach(DataColumn col in table.Columns)
             {
                  colIndex++;
                  excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();
             }
         }
         excel.Visible=false;   
         excel.ActiveWorkbook.SaveAs(strExcelFileName+".XLS",Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null,null);
         excel.Quit();
         excel=null;
         GC.Collect();//垃圾回收
    }
    #endregion
    利用.NET组件打印
    利用.NET组件
    • 优点:这种打印方式对于格式变化大,数据量小的应用来说非常合适。
    • 缺点:
    – 需要客户端安装NET framework组件。
    – XML的解析上,如果文件较大速度上不是很理想。
    – 页面首次加载时会有明显的延时。

    使用XSL和XSLT转换XML
    • XSL:扩展样式表语言,可以通过它来把XML转换为其他的文本格式
    • XSL转换包括发现或者选择一个模式匹配,通过使用XPath选择一个结果集,然后对结果集中的每一项,为这些匹配定义结果输出。
    • XSL是一个功能强大的工具,可以把XML转换成任何你想要的格式。
    【参考代码】
    XslTransform xslt = new XslTransform();
    xslt.Load(Server.MapPath( "StudentsToHTML.xsl") );

    XPathDocument XDoc = new XPathDocument(Server.MapPath( "Students.XML" ));
    XmlWriter writer = new XmlTextWriter( Server.MapPath("Students.html"), System.Text.Encoding.UTF8 );
    xslt.Transform( XDoc, null, writer );
    writer.Close();
    Response.Redirect("Students.html");
    利用ActiveX控件打印
    利用第三方控件
    • 自己开发控件。这种方式很多商用软件采用这种方式,写成控件后已经无所谓是在web中使用还是应用程序中使用了。
    • 优点:打印方式非常灵活,基本上程序能做到的web也能做得到。
    • 缺点:客户端需要安装组件,部署不是很方便。
    使用水晶报表
    • 用户仅需要Web 浏览器就可以查看报表
    • 报表查看器控件可以是应用程序中众多控件之一。
    • 与报表轻松交互
    • 用户可将报表导出为Microsoft Word 和Excel 格式,以及PDF、HTML 和Crystal Reports for Visual Studio .NET格式。
    • 可以使用报表控件直接打印

    【实例代码】
    //水晶报表的填充,省略连接代码
    myReport ReportDoc = new myReport();
    ReportDoc.SetDataSource(ds);
    Crv.ReportSource = ReportDoc;

    //输出为指定类型文件
    CrystalDecisions.Shared.DiskFileDestinationOptions DiskOpts = new          CrystalDecisions.Shared.DiskFileDestinationOptions();
    ReportDoc.ExportOptions.ExportDestinationType = CrystalDecisions.Shared.ExportDestinationType.DiskFile;
    string strFileName = Server.MapPath("Output");
    switch (ddlFormat.SelectedItem.Text)
    {
         case "Rich Text (RTF)":
                  ReportDoc.ExportOptions.ExportFormatType =   CrystalDecisions.Shared.ExportFormatType.RichText;
                  DiskOpts.DiskFileName =strFileName + ".rtf";
             break;
         case "Portable Document (PDF)":
                  ReportDoc.ExportOptions.ExportFormatType =   CrystalDecisions.Shared.ExportFormatType.PortableDocFormat;
                  DiskOpts.DiskFileName = strFileName + ".pdf";
             break;
         case "MS Word (DOC)":
                  ReportDoc.ExportOptions.ExportFormatType =   CrystalDecisions.Shared.ExportFormatType.WordForWindows;
                  DiskOpts.DiskFileName = strFileName + ".doc";
             break;
         case "MS Excel (XLS)":
                  ReportDoc.ExportOptions.ExportFormatType =   CrystalDecisions.Shared.ExportFormatType.Excel;//
                  DiskOpts.DiskFileName = strFileName + ".xls";
             break;
         default:
             break;
    }
    ReportDoc.ExportOptions.DestinationOptions = DiskOpts;
    ReportDoc.Export();

    //打印
    // 指定打印机名称  
    string strPrinterName;
    strPrinterName = @"Canon Bubble-Jet BJC-210SP";
    // 设置打印页边距
    PageMargins margins;
    margins = ReportDoc.PrintOptions.PageMargins;
    margins.bottomMargin = 250;
    margins.leftMargin = 350;
    margins.rightMargin = 350;
    margins.topMargin = 450;    
    ReportDoc.PrintOptions.ApplyPageMargins(margins);    
    //应用打印机名称
    ReportDoc.PrintOptions.PrinterName = strPrinterName;    
    // 打印   // 打印报表。将startPageN 和endPageN
    // 参数设置为0 表示打印所有页。
    ReportDoc.PrintToPrinter(1, false,0,0);    

    =========================================

    用控件,先设置一下
    <object id="WebBrowser" width=0 height=0 classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2">
    </object>
    <input name="printformview" type="button" value="打印机设置" onClick=document.all.WebBrowser.ExecWB(6,1) class="button">
    <input name="printform2" type="button" value="页面设置" onClick=document.all.WebBrowser.ExecWB(8,1) class="button">
    <input name="printform" type="button" value="直接打印" onClick=document.all.WebBrowser.ExecWB(6,6) class="button">

  • 相关阅读:
    Linux下SSH的Log文件路径
    Linux下压缩与解压命令tar
    Linux命令之at
    Linux下nice/renice命令小结
    Linux命令详解nice
    LVM---动态调整磁盘容量
    VT100字体
    Linux命令之WC
    for name in loop Shell
    Bind9用view配主从
  • 原文地址:https://www.cnblogs.com/wanglinglong/p/1576888.html
Copyright © 2011-2022 走看看